可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has answers here:
Closed 6 years ago.
For example, I have an array like this;
var arr = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7, 8, 9, 10, 10]
My purpose is to discard repeating elements from array and get final array like this;
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
How can this be achieved in JavaScript?
NOTE: array is not sorted, values can be arbitrary order.
回答1:
It's easier using Array.filter
:
var unique = arr.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
回答2:
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.
回答3:
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
回答4:
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);
});
回答5:
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!)