本文翻译自:Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
I need to check a JavaScript array to see if there are any duplicate values. 我需要检查一个JavaScript数组,看看是否有重复的值。 What's the easiest way to do this? 最简单的方法是什么? I just need to find what the duplicated values are - I don't actually need their indexes or how many times they are duplicated. 我只需要查找重复的值是什么-我实际上不需要它们的索引或它们被重复多少次。
I know I can loop through the array and check all the other values for a match, but it seems like there should be an easier way. 我知道我可以遍历数组并检查所有其他值是否匹配,但是似乎应该有一种更简单的方法。
Similar question: 类似的问题:
#1楼
参考:https://stackoom.com/question/3Wiz/获取数组中的所有非唯一值-即-重复-多次出现
#2楼
ES5 only (ie, it needs a filter() polyfill for IE8 and below): 仅适用于ES5(即,它需要针对IE8及更低版本的filter()polyfill):
var arrayToFilter = [ 4, 5, 5, 5, 2, 1, 3, 1, 1, 2, 1, 3 ];
arrayToFilter.
sort().
filter( function(me,i,arr){
return (i===0) || ( me !== arr[i-1] );
});
#3楼
using underscore.js 使用underscore.js
function hasDuplicate(arr){
return (arr.length != _.uniq(arr).length);
}
#4楼
var input = ['a', 'b', 'a', 'c', 'c'],
duplicates = [],
i, j;
for (i = 0, j = input.length; i < j; i++) {
if (duplicates.indexOf(input[i]) === -1 && input.indexOf(input[i], i+1) !== -1) {
duplicates.push(input[i]);
}
}
console.log(duplicates);
#5楼
Here is a very light and easy way: 这是一个非常简便的方法:
var codes = dc_1.split(',');
var i = codes.length;
while (i--) {
if (codes.indexOf(codes[i]) != i) {
codes.splice(i,1);
}
}
#6楼
I think the below is the easiest and fastest O(n) way to accomplish exactly what you asked: 我认为以下是完成您所要求的最简单,最快的O(n)方法:
function getDuplicates( arr ) {
var i, value;
var all = {};
var duplicates = [];
for( i=0; i<arr.length; i++ ) {
value = arr[i];
if( all[value] ) {
duplicates.push( value );
all[value] = false;
} else if( typeof all[value] == "undefined" ) {
all[value] = true;
}
}
return duplicates;
}
Or for ES5 or greater: 或对于ES5或更高版本:
function getDuplicates( arr ) {
var all = {};
return arr.reduce(function( duplicates, value ) {
if( all[value] ) {
duplicates.push(value);
all[value] = false;
} else if( typeof all[value] == "undefined" ) {
all[value] = true;
}
return duplicates;
}, []);
}