从数组中删除重复的元素

例如,我有一个这样的数组;

var arr = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7, 8, 9, 10, 10]

我的目的是从数组中丢弃重复的元素,得到像这样的最终数组;

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

如何在 JavaScript 中实现这一点?

注意: 数组没有排序,值可以是任意顺序。

247250 次浏览

As elements are yet ordered, you don't have to build a map, there's a fast solution :

var newarr = [arr[0]];
for (var i=1; i<arr.length; i++) {
if (arr[i]!=arr[i-1]) newarr.push(arr[i]);
}

If your array weren't sorted, you would use a map :

var newarr = (function(arr){
var m = {}, newarr = []
for (var i=0; i<arr.length; i++) {
var v = arr[i];
if (!m[v]) {
newarr.push(v);
m[v]=true;
}
}
return newarr;
})(arr);

Note that this is, by far, much faster than the accepted answer.

you may try like this using jquery

 var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];
var uniqueVals = [];
$.each(arr, function(i, el){
if($.inArray(el, uniqueVals) === -1) uniqueVals.push(el);
});

Try following from Removing duplicates from an Array(simple):

Array.prototype.removeDuplicates = function (){
var temp=new Array();
this.sort();
for(i=0;i<this.length;i++){
if(this[i]==this[i+1]) {continue}
temp[temp.length]=this[i];
}
return temp;
}

Edit:

This code doesn't need sort:

Array.prototype.removeDuplicates = function (){
var temp=new Array();
label:for(i=0;i<this.length;i++){
for(var j=0; j<temp.length;j++ ){//check duplicates
if(temp[j]==this[i])//skip if already present
continue label;
}
temp[temp.length] = this[i];
}
return temp;
}

(But not a tested code!)

var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];


function squash(arr){
var tmp = [];
for(var i = 0; i < arr.length; i++){
if(tmp.indexOf(arr[i]) == -1){
tmp.push(arr[i]);
}
}
return tmp;
}


console.log(squash(arr));

Working Example http://jsfiddle.net/7Utn7/

Compatibility for indexOf on old browsers

It's easier using Array.filter:

var unique = arr.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})