如何从 JavaScript 中包含重复项的数组中获取唯一值数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13486479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get an array of unique values from an array containing duplicates in JavaScript?
提问by NaveenDAlmeida
Given a ['0','1','1','2','3','3','3']array, the result should be ['0','1','2','3'].
给定一个['0','1','1','2','3','3','3']数组,结果应该是['0','1','2','3']。
回答by Pedro L.
Edited
已编辑
ES6 solution:
ES6解决方案:
[...new Set(a)];
Alternative:
选择:
Array.from(new Set(a));
Old response. O(n^2) (do not use it with large arrays!)
旧回复。O(n^2)(不要在大数组中使用它!)
var arrayUnique = function(a) {
return a.reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
};
回答by beatgammit
If you want to maintain order:
如果你想维持秩序:
arr = arr.reverse().filter(function (e, i, arr) {
return arr.indexOf(e, i+1) === -1;
}).reverse();
Since there's no built-in reverse indexof, I reverse the array, filter out duplicates, then re-reverse it.
由于没有内置的反向索引,我反转数组,过滤掉重复项,然后重新反转它。
The filter function looks for any occurence of the element after the current index (before in the original array). If one is found, it throws out this element.
filter 函数查找当前索引之后(原始数组中的之前)元素的任何出现。如果找到一个,它会抛出这个元素。
Edit:
编辑:
Alternatively, you could use lastindexOf (if you don't care about order):
或者,您可以使用 lastindexOf (如果您不关心订单):
arr = arr.filter(function (e, i, arr) {
return arr.lastIndexOf(e) === i;
});
This will keep unique elements, but only the last occurrence. This means that ['0', '1', '0'] becomes ['1', '0'], not ['0', '1'].
这将保留唯一元素,但仅保留最后一次出现的元素。这意味着 ['0', '1', '0'] 变为 ['1', '0'],而不是 ['0', '1']。
回答by mahesh
Here is an Array Prototype function:
这是一个数组原型函数:
Array.prototype.unique = function() {
var unique = [];
for (var i = 0; i < this.length; i++) {
if (unique.indexOf(this[i]) == -1) {
unique.push(this[i]);
}
}
return unique;
};
回答by fguillen
回答by OhJeez
It's 2014 now guys, and time complexity still matters!
现在是 2014 年了,时间复杂度仍然很重要!
array.filter(function() {
var seen = {};
return function(element, index, array) {
return !(element in seen) && (seen[element] = 1);
};
}());
回答by Raekye
function array_unique(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) == -1) {
result.push(arr[i]);
}
}
return result;
}
Not a built in function. If the product list does not contain the item, add it to unique list and return unique list.
不是内置函数。如果产品列表不包含该项目,则将其添加到唯一列表并返回唯一列表。
回答by Julius Loa
There you go! You are welcome!
你去吧!不客气!
Array.prototype.unique = function()
{
var tmp = {}, out = [];
for(var i = 0, n = this.length; i < n; ++i)
{
if(!tmp[this[i]]) { tmp[this[i]] = true; out.push(this[i]); }
}
return out;
}
var a = [1,2,2,7,4,1,'a',0,6,9,'a'];
var b = a.unique();
alert(a);
alert(b);
回答by CMCDragonkai
You can find all kinds of array unique implementations here:
您可以在此处找到各种数组唯一实现:
http://jsperf.com/distinct-hash-vs-comparison/12
http://jsperf.com/distinct-hash-vs-comparison/12
http://jsperf.com/array-unique-functional
http://jsperf.com/array-unique-functional
I prefer functional styles such as:
我更喜欢功能性风格,例如:
var arr = ['lol', 1, 'fdgdfg', 'lol', 'dfgfg', 'car', 1, 'car', 'a', 'blah', 'b', 'c', 'd', '0', '1', '1', '2', '3', '3', '3', 'crazy', 'moot', 'car', 'lol', 1, 'fdgdfg', 'lol', 'dfgfg', 'car', 1, 'car', 'a', 'blah', 'b', 'c', 'd', '0', '1', '1', '2', '3', '3', '3', 'crazy', 'moot', 'car', 'lol', 1, 'fdgdfg'];
var newarr = arr.reduce(function (prev, cur) {
//console.log(prev, cur);
if (prev.indexOf(cur) < 0) prev.push(cur);
return prev;
}, []);
var secarr = arr.filter(function(element, index, array){
//console.log(element, array.indexOf(element), index);
return array.indexOf(element) >= index;
});
//reverses the order
var thirdarr = arr.filter(function (e, i, arr) {
//console.log(e, arr.lastIndexOf(e), i);
return arr.lastIndexOf(e) === i;
});
console.log(newarr);
console.log(secarr);
console.log(thirdarr);
回答by Amiga500Kid
No redundant "return" array, no ECMA5 (I'm pretty sure!) and simple to read.
没有多余的“返回”数组,没有 ECMA5(我很确定!)并且易于阅读。
function removeDuplicates(target_array) {
target_array.sort();
var i = 0;
while(i < target_array.length) {
if(target_array[i] === target_array[i+1]) {
target_array.splice(i+1,1);
}
else {
i += 1;
}
}
return target_array;
}
回答by Mitul Maheshwari
Here is the way you can do remove duplicate values from the Array.
这是您可以从数组中删除重复值的方法。
function ArrNoDupe(dupArray) {
var temp = {};
for (var i = 0; i < dupArray.length; i++) {
temp[dupArray[i]] = true;
var uniqueArray = [];
for (var k in temp)
uniqueArray.push(k);
return uniqueArray;
}
}

