我有一个数组,它有一些值,但我不需要在我的数组中有相同的值
例子:
var myarray=new Array();
myarray[0]="Apple",
myarray[1]="Grapes",
myarray[2]="Apple",
我希望我的数组应该只包含葡萄和苹果。
我有一个数组,它有一些值,但我不需要在我的数组中有相同的值
例子:
var myarray=new Array();
myarray[0]="Apple",
myarray[1]="Grapes",
myarray[2]="Apple",
我希望我的数组应该只包含葡萄和苹果。
在这里我找到了一些方法。来源: 删除数组中的重复元素
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;
}
此函数将从数组中删除重复值(它保留最后一个):
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;
}
}
}
如果你想保留第一个而不是最后一个,你可以使用这个版本:
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.