This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove duplicates from an array of objects in javascript
I'm trying to remove any duplicates in an array. For example if I have 112233 I want to return only 123.
My code:
function array_unique(array) {
var array_length = array.length;
var new_array = [];
for (var i = 0; i < array_length; i++) {
if (array[i] == array[i + 1]) {
}
new_array.push(array[i]);
}
return new_array;
}
I don't know what to type in the if so I can remove the doubles
Here you can remove the duplicates with complexity O(n).
var elems = {},
arr = [1,2,1,1,2,3,3,3,3,4];
arr = arr.filter(function (e) {
if (elems[e] === undefined) {
elems[e] = true;
return true;
}
return false;
});
I use the elems hash (object) to remember all already existing elements. If the current element is a key in the elems hash I just filter it.
Use prototype for Array like this
Array.prototype.removeDups = function(){
var local_array = this;
return local_array.filter(function(elem, pos) {
return local_array.indexOf(elem) == pos;
});
}
arrayWithNoDuplicates = new_array.filter(function(element, position) {
return myArray.indexOf(element) == position;
})
fxnUniqOptns = function (array) {
var oOptns = [];
$.each(array, function (i, val) {
if ($.inArray(val, oOptns) == -1)
oOptns.push(val);
});
oOptns = oOptns.sort();
return oOptns;
}
give array.splice(i, 1) after the if condition,this will remove the current element,so that duplicates will be removed.
Related
This question already has answers here:
Remove items from array with splice in for loop [duplicate]
(5 answers)
Closed 6 years ago.
i have created an array for vowels position in string now i want reomve all elements that have value -1 from this array but its not working
function translatePigLatin(str) {
var vowelp=[];
var newarr=str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel=vowelp[0];
for(var i=0;i<vowelp.length;i++) { //looping through vowel's position array
if(vowelp[i]==-1) {
vowelp.splice(i,1);
console.log(vowelp[i]);
}
}
return vowelp;
}
input-translatePigLatin("consonant");
output that i am getting is[6,-1,1] but i want [6,1]
Simple way is to use filter()
function translatePigLatin(str) {
var vowelp = [];
var newarr = str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel = vowelp[0];
return vowelp.filter(function(v) {
return v != -1;
})
}
console.log(translatePigLatin("consonant"));
In your case you need to decrement the value of i in case of item removal otherwise it will skip the next element.
function translatePigLatin(str) {
var vowelp = [];
var newarr = str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel = vowelp[0];
for (var i = 0; i < vowelp.length; i++) { //looping through vowel's position array
if (vowelp[i] == -1) {
vowelp.splice(i, 1);
i--;
console.log(vowelp[i]);
}
}
return vowelp;
}
console.log(translatePigLatin("consonant"));
You can make it more simple using map() and filter() with an array
function translatePigLatin(str) {
return ['a', 'e', 'i', 'o', 'u'].map(function(v) {
return str.indexOf(v);
}).filter(function(v) {
return v != -1;
});
}
console.log(translatePigLatin("consonant"));
you are calling splice on the same array you are iterating over. Rememeber splice is mutable and it deletes from the original array. As a result of that your index tracking logic is getting messed up. So instead you could use delete[i] (which does not mess up the indexes and creates a void)
function translatePigLatin(str) {
var vowelp=[];
var newarr=str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel=vowelp[0];
for(var i=0;i<vowelp.length;i++) { //looping through vowel's position array
if(vowelp[i]==-1) {
delete vowelp[i];
}
}
return vowelp;
}
console.log(translatePigLatin("consonant")); //prints [6, 3: 1]
which means you have 6 at index 0 and 1 at index 3
I would prefer a simpler code:
function translatePigLatin(str) {
var vowelp = [];
var vowels = ['a','e','i','o','u'];
for (var i = 0; i < vowels.length; i++) {
var index = str.indexOf(vowels[i]);
if (index != -1) {
vowelp.push(index);
}
}
return vowelp;
}
I am trying to achieve something which seemed very basic but is getting me mad over the last days.
I have a simple array : ["a","b","c","d","e"] and I want to turn it into a nested JSON like this:
{"a":{"b":{"c":{"d":{"e":""}}}}}
Looping over it, I ran in problems like "how do you save the last key to set it afterwards without erasing it" and so on.
Does anyone has an idea?
You might have had problems because you were looping in the wrong direction. Try to build the object from inside-out:
array.reduceRight(function(v, key) {
var o = {};
o[key] = v;
return o;
}, "")
or, with a loop:
var val = "";
for (var i=array.length; i--; )
var o = {};
o[array[i]] = val;
val = o;
}
return val;
Here's one way to do it, recursively:
function convertToNestedObject(arr) {
var result = {};
if (arr.length === 1) {
result[arr[0]] = '';
} else {
result[arr[0]] = convertToNestedObject(arr.slice(1, arr.length));
}
return result;
}
You could pass the start index in to the function instead of using slice and creating copies of the array:
function convertToNestedObject(arr, startIndex) {
var result = {};
if (arr.length - startIndex === 1) {
result[arr[startIndex]] = '';
} else {
result[arr[startIndex]] = convertToNestedObject(arr, startIndex + 1);
}
return result;
}
Example: http://jsfiddle.net/jwcxfaeb/1/
Put current element as key and empty object ({}) as value. Continue with newly inserted empty object.
function toNested(arr){
var nested = {};
var temp = nested;
for(var i=0; i<arr.length; i++){
temp[arr[i]] = {};
temp = temp[arr[i]];
}
return nested;
}
If I have an array like this:
var array = [{ID:1,value:'test1'},
{ID:3,value:'test3'},
{ID:2,value:'test2'}]
I want to select an index by the ID.
i.e, I want to somehow select ID:3, and get {ID:3,value:'test3'}.
What is the fastest and most lightweight way to do this?
Use array.filter:
var results = array.filter(function(x) { return x.ID == 3 });
It returns an array, so to get the object itself, you'd need [0] (if you're sure the object exists):
var result = array.filter(function(x) { return x.ID == 3 })[0];
Or else some kind of helper function:
function getById(id) {
var results = array.filter(function(x) { return x.ID == id });
return (results.length > 0 ? results[0] : null);
}
var result = getById(3);
With lodash you can use find with pluck-style input:
_.find(result, {ID: 3})
Using filter is not the fastest way because filter will always iterate through the entire array even if element being search for is the first element. This can perform poorly on larger arrays.
If you are looking for fastest way, simply looping through until the element is found might be best option. Something like below.
var findElement = function (array, inputId) {
for (var i = array.length - 1; i >= 0; i--) {
if (array[i].ID === inputId) {
return array[i];
}
}
};
findElement(array, 3);
I would go for something like this:
function arrayObjectIndexOf(myArray, property, searchTerm) {
for (var i = 0, len = myArray.length; i < len; i++) {
if (myArray[i].property === searchTerm)
return myArray[i];
}
return -1;
}
In your case you should do:
arrayObjectIndexOf(array, id, 3);
var indexBy = function(array, property) {
var results = {};
(array||[]).forEach(function(object) {
results[object[property]] = object;
});
return results
};
which lets you var indexed = indexBy(array, "ID");
This question already has answers here:
Getting index of an array's element based on its properties
(7 answers)
Closed 9 years ago.
My array looks something like this:
var someArray =
[
{ id: 'someID', name: 'someName', title: 'someTitle' },
{ id: 'anotherID', name: 'anotherName', title: 'anotherTitle' },
{ id: 'otherID', name: 'otherName', title: 'otherTitle' }
];
I want to get index reference of an object that who's id === 'anotherID' in reference with someArray
I know that I can use $.grep() to return an object:
var resultArray = $.grep(columns, function(e){return e.id === 'anotherID'});
resultArray will return an array of objects that match the condition of anonymous function, but it will not return an index of that object in someArray
I am looking for JavaScript/Jquery solution.
Thank you.
A simple for:
var elementIndex = false;
for ( var index = 0, length = someArray.length; index < length; index++ ) {
if ( someArray[index].id === 'anotherID' ) {
elementIndex = index;
break;
}
}
if ( elementIndex !== false ) {
console.log(elementIndex);
}
The easiest way is going to be to write your own function (unless you have access to the built-in indexOf method and it works for you:
var indexOf = function(array, predicate) {
for(var i = 0; i < array.length; i++) {
if(predicate(array[i])) {
return i;
}
}
return -1;
}
Which you could then call like:
var index = indexOf(someArray, function(e){ return e.id === 'anotherID'; });
.reduce() is not supported by IE8
One liner using reduce:
someArray.reduce(function(p,c,i){return c.id=='anotherID'?i:p},-1);
Using jQuery's $.each:
var posIndex = '';
$.each(someArray, function(i){
if(someArray[i].id === 'anotherID'){
posIndex = i;
return false; /*Stop iterating once found. Tip from Felix Kling*/
}
});
See example fiddle (upper code part).
As you see, using jQuery is alot easier than normal JS for.
This answer considers that each id is really an identifier (a.k.a. unique) or else posIndex will return the position of the last object which has anotherID.
Update
Added 'Felix Kling' tip of return false;. Now it will return the first match only. If have more than one id with same value, use below. Thanks Felix.
If you think that might have multiple equal ids, I suggest that posIndex becomes an array and then you read the array later. Example:
var posIndexArray = [];
$.each(someOtherArray, function (i) {
if (someOtherArray[i].id === 'anotherID') {
posIndexArray.push(i);
}
});
And posIndexArray will be a comma separated list of indexes you can then use $.each on it to do whatever you want with the indexes.
See example fiddle (lower code part).
You can achieve this pretty easily using either plain ol' JavaScript or jQuery if you so choose!
le vanilla
function getById(id, objects) {
for (var i = 0, length = objects.length; i < length; i++) {
if (objects[i].id === id) {
return i;
}
}
return -1;
}
jQueryyy
function getById(id, objects) {
var index = -1;
$.each(objects, function(i) {
if (this.id === id) {
index = i;
return false;
}
});
return index;
}
From that point, you could just call your little handy-dandy helper function and check that you got a good index.
var index = getById('otherId', someArray);
if (~index) {
doSomethingAwesome(someArray[index]);
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Easiest way to find duplicate values in a JavaScript array
Javascript array sort and unique
I have the following array
var output = new array(7);
output[0]="Rose";
output[1]="India";
output[2]="Technologies";
output[3]="Rose";
output[4]="Ltd";
output[5]="India";
output[6]="Rose";
how can i remove the duplicate elements in above array.Is there any methods to do it?
You can write a function like this
function eliminateDuplicates(arr) {
var i,
len=arr.length,
out=[],
obj={};
for (i=0;i<len;i++) {
obj[arr[i]]=0;
}
for (i in obj) {
out.push(i);
}
return out;
}`
Check this here
Maybe more complex than you need but:
function array_unique (inputArr) {
// Removes duplicate values from array
var key = '',
tmp_arr2 = {},
val = '';
var __array_search = function (needle, haystack) {
var fkey = '';
for (fkey in haystack) {
if (haystack.hasOwnProperty(fkey)) {
if ((haystack[fkey] + '') === (needle + '')) {
return fkey;
}
}
}
return false;
};
for (key in inputArr) {
if (inputArr.hasOwnProperty(key)) {
val = inputArr[key];
if (false === __array_search(val, tmp_arr2)) {
tmp_arr2[key] = val;
}
}
}
return tmp_arr2;
}
Code taken from: http://phpjs.org/functions/array_unique:346
You can remove dups from an array by using a temporary hash table (using a javascript object) to keep track of which images you've already seen in the array. This works for array values that can be uniquely represented as a string (strings or numbers mostly), but not for objects.
function removeDups(array) {
var index = {};
// traverse array from end to start
// so removing the current item from the array
// doesn't mess up the traversal
for (var i = array.length - 1; i >= 0; i--) {
if (array[i] in index) {
// remove this item
array.splice(i, 1);
} else {
// add this value to index
index[array[i]] = true;
}
}
}
Here's a working example: http://jsfiddle.net/jfriend00/sVT7g/
For sizable arrays, using an object as a temporary index will be many times faster than a linear search of the array.
First of all, you'll want to use the array literal (var output = []) to declare your array. Second, you'll want to loop through your array and store all the values in a second array. If any value in the first array matches a value in the second array, delete it and continue looping.
Your code would look like this:
var output = [
"Rose",
"India",
"Technologies",
"Rose",
"Ltd",
"India",
"Rose"
]
var doubledOutput = [];
for(var i = 0; i < output.length; i++) {
var valueIsInArray = false;
for(var j = 0; j < doubledOutput.length; j++) {
if(doubledOutput[j] == output[i]) {
valueIsInArray = true;
}
}
if(valueIsInArray) {
output.splice(i--, 1);
} else {
doubledOutput.push(output[i]);
}
}
Please note, the above code is untested and may contain errors.