# JS数组去重方法最优解

31.8k 次浏览

ceteve 70
2013-08-08 提问
11 个回答
``````function unique(array){
var n = [];//临时数组
for(var i = 0;i < array.length; i++){
if(n.indexOf(array[i]) == -1) n.push(array[i]);
}
return n;
}``````
1

`var arr = [ 1, 2, 1, 2, '1', '11'];`这个例子也通过不了吧……

1

2

tinkgu · 2016年11月21日

ES6：

``Array.from(new Set(arr));``
``````
var arr = [1,3,1,4,1,5,6,3,1,2];

Array.from(new Set(arr));//[1, 3, 4, 5, 6, 2]``````

``````function distinct(arr) {
var obj = {},
i = 0,
len = 0;
if (Array.isArray(arr) && arr.length > 0) {
len = arr.length;
for (i = 0; i < len; i += 1) {
obj[arr[i]] = arr[i];
}
return Object.keys(obj);
}
return [];
}``````

``````var arr = ["1","2","3","4","5","4","3"];
var uniqueArr = [];
\$.each(arr, function(i, el){
if(\$.inArray(el, uniqueArr) === -1) uniqueArr.push(el);
});
``````

``````var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var sortedArr = arr.sort();
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
if (sortedArr[i + 1] == sortedArr[i]) {
results.push(sortedArr[i]);
}
}

``````
3

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var sortedArr = arr.sort();
console.log(sortedArr);
var results = [];
for (var i = 0; i < arr.length; i++) {

``````if (sortedArr[i + 1] !== sortedArr[i]) {
results.push(sortedArr[i]);
}``````

}

jun_jun · 2016年09月08日

``````var arr = [1, 2, 3, "1", "a", "a", "3", 5, "2", "5", 1, 2, 3, 5];

function reDuplicates(arr) {
var newArr = [];
for(var i = 0, len = arr.length; i < len; i ++) {
for(var j = 0; j < newArr.length; j ++) {
var bol;
if(bol = ~function() {
if(arr[i] === newArr[j])
return -2;
return -1;
}())
break;
}
if(bol)
continue;
newArr.push(arr[i]);
}
return newArr;
}
console.log(arr);
console.log(reDuplicates(arr));``````

// [1, 2, 3, "1", "a", "a", "3", 5, "2", "5", 1, 2, 3, 5]
// [1, 2, 3, "1", "a", "3", 5, "2", "5"]

``````Array.prototype.unique = function() {
var res = []
var json = {}
for (var i = 0; i < this.length; i++) {
if(!json[this[i]]){ // 利用对象属性不重复
res.push(this[i])
json[this[i]] = 1  // 传值随意
}
}
return res
}
/*你就可以像下面这样调用该函数了*/
var arr = [2,4,66,55,33,55,3,4,4,32,2]
console.log(arr.unique())``````

``````function unique(array) {
var n = []
var nflag = false
for (var i = 0; i < array.length; i++) {
if (isNaN(array[i]) && !nflag && typeof array[i] == 'number') {
nflag = true
n.push(array[i])
}
if (n.indexOf(array[i]) === -1) {
if (!isNaN(array[i]) || typeof array[i] !== 'number') {
n.push(array[i])
}
}
}
return n;
}``````