I have the an array which have some values but i need not want the same value in my array
Example:
var myarray=new Array();
myarray[0]="Apple",
myarray[1]="Grapes",
myarray[2]="Apple",
i want my array should contain only grapes and apple.
I have the an array which have some values but i need not want the same value in my array
Example:
var myarray=new Array();
myarray[0]="Apple",
myarray[1]="Grapes",
myarray[2]="Apple",
i want my array should contain only grapes and apple.
Here i found some method. Source: Removing duplicate element in an array
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;
}
This function will remove duplicate values from an array (it keeps the last one):
function removeDups(arr) {
var temp = {}, val;
for (var i = arr.length - 1; i >= 0; i--) {
val = arr[i];
if (temp[val] === true) {
// already have one of these so remove this one
arr.splice(i, 1);
} else {
temp[val] = true;
}
}
}
If you want to keep the first one instead of the last one, you can use this version:
function removeDups(arr) {
var temp = {}, val;
for (var i = 0; i < arr.length; i++) {
val = arr[i];
if (temp[val] === true) {
// already have one of these so remove this one
arr.splice(i, 1);
// correct our for loop index to account for removing the current item
--i;
} else {
temp[val] = true;
}
}
}
unique = myArray.filter(function(elem, pos) {
return myArray.indexOf(elem) == pos;
})
unique
will have only unique values.
Note: The above relies on filter
, which is new as of ECMAScript5 and not present in legacy browsers (including IE8), but present in all modern ones. If you have to support legacy browsers, use an ES5 shim (as filter
is shim-able). Also note that indexOf
may not be present in really old browsers like IE7.