我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
http://jsfiddle.net/vol7ron/gfJ28/
var arr = ['hello','goodbye','foo','hello','foo','bar',1,2,3,4,5,6,7,8,9,0,1,2,3];
var hash = [];
// build hash
for (var n=arr.length; n--; ){
if (typeof hash[arr[n]] === 'undefined') hash[arr[n]] = [];
hash[arr[n]].push(n);
}
// work with compiled hash (not necessary)
var duplicates = [];
for (var key in hash){
if (hash.hasOwnProperty(key) && hash[key].length > 1){
duplicates.push(key);
}
}
alert(duplicates);
The result will be the hash array, which will contain both a unique set of values and the position of those values. So if there are 2 or more positions, we can determine that the value has a duplicate. Thus, every place hash[<value>].length > 1, signifies a duplicate. hash['hello'] will return [0,3] because 'hello' was found in node 0 and 3 in arr[]. Note: the length of [0,3] is what's used to determine if it was a duplicate. Using for(var key in hash){ if (hash.hasOwnProperty(key)){ alert(key); } } will alert each unique value.
其他回答
这是我用map实现的。它应该运行在O(n)时间,应该有点容易喘气。
var first_array = [1, 1, 2, 3, 4, 4, 5, 6); var find_dup=new Map; For (first_array的const迭代器){ //如果现值++ 如果(find_dup.has (iterator)) { find_dup.set(迭代器,find_dup.get(迭代器)+ 1); 其他}{ //否则添加 find_dup.set(迭代器,1); } } console.log (find_dup.get (2));
然后你可以find_dup.get(key)来查找它是否有重复(它应该给> 1)。
更新:以下使用一个优化的组合策略。它优化了原语查找,以受益于散列O(1)查找时间(在原语数组上惟一地运行是O(n))。对象查找通过在遍历对象时用唯一id标记对象来优化,因此识别重复对象也是每个项目O(1),整个列表O(n)。唯一的例外是被冻结的项目,但这种情况很少见,并且使用数组和indexOf提供了一个回退。
var unique = function(){
var hasOwn = {}.hasOwnProperty,
toString = {}.toString,
uids = {};
function uid(){
var key = Math.random().toString(36).slice(2);
return key in uids ? uid() : uids[key] = key;
}
function unique(array){
var strings = {}, numbers = {}, others = {},
tagged = [], failed = [],
count = 0, i = array.length,
item, type;
var id = uid();
while (i--) {
item = array[i];
type = typeof item;
if (item == null || type !== 'object' && type !== 'function') {
// primitive
switch (type) {
case 'string': strings[item] = true; break;
case 'number': numbers[item] = true; break;
default: others[item] = item; break;
}
} else {
// object
if (!hasOwn.call(item, id)) {
try {
item[id] = true;
tagged[count++] = item;
} catch (e){
if (failed.indexOf(item) === -1)
failed[failed.length] = item;
}
}
}
}
// remove the tags
while (count--)
delete tagged[count][id];
tagged = tagged.concat(failed);
count = tagged.length;
// append primitives to results
for (i in strings)
if (hasOwn.call(strings, i))
tagged[count++] = i;
for (i in numbers)
if (hasOwn.call(numbers, i))
tagged[count++] = +i;
for (i in others)
if (hasOwn.call(others, i))
tagged[count++] = others[i];
return tagged;
}
return unique;
}();
如果你有ES6集合可用,那么有一个更简单、更快的版本。(shim适用于IE9+和其他浏览器:https://github.com/Benvie/ES6-Harmony-Collections-Shim)
function unique(array){
var seen = new Set;
return array.filter(function(item){
if (!seen.has(item)) {
seen.add(item);
return true;
}
});
}
这应该是在数组中查找重复值的最短和最简单的方法之一。
Var arr = [1,2,3,4,5,6,7,8,1,2,3,4,5,3,4]; Var数据= arr.filter(函数(项目,索引,arr){ 返回arr.indexOf(item) != arr.lastIndexOf(item) && arr.indexOf(item) == index; }) console.log(数据);
这里有一个非常简单的方法:
var codes = dc_1.split(',');
var i = codes.length;
while (i--) {
if (codes.indexOf(codes[i]) != i) {
codes.splice(i,1);
}
}
在一次采访中有人问我这个问题,我的回答是,
List<int> getDublicates(List<int> x)
{
List<int> result = new List<int>();
while (x.Count>0)
{
int d = x[0];
x.Remove(x[0]);
if (x.Contains(d))
result.Add(d);
}
return result;
}
它的性能很好