我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
只是在上面的基础上补充一些理论。
在比较模型中,查找重复项的下界为O(n*log(n))。所以理论上,你不能做得比先排序然后再进行 按顺序列出,删除你找到的任何重复项。
如果你想在线性(O(n))的期望时间内找到重复项,你可以做到 哈希列表的每个元素;如果有冲突,删除/标记为重复, 并继续。
其他回答
更新:以下使用一个优化的组合策略。它优化了原语查找,以受益于散列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;
}
});
}
这是一个方法,以避免重复到javascript数组…它支持字符串和数字…
var unique = function(origArr) {
var newArray = [],
origLen = origArr.length,
found,
x = 0; y = 0;
for ( x = 0; x < origLen; x++ ) {
found = undefined;
for ( y = 0; y < newArray.length; y++ ) {
if ( origArr[x] === newArray[y] ) found = true;
}
if ( !found) newArray.push( origArr[x] );
}
return newArray;
}
检查这个小提琴..
我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
这是一个有趣而简单的任务,有许多难以阅读的答案……
打印稿
function getDuplicatedItems<T>(someArray: T[]): T[] {
// create a set to iterate through (we only need to check each value once)
const itemSet = new Set<T>(someArray);
// from that Set, we check if any of the items are duplicated in someArray
const duplicatedItems = [...itemSet].filter(
(item) => someArray.indexOf(item) !== someArray.lastIndexOf(item)
);
return duplicatedItems;
}
JavaScript
function getDuplicatedItems(someArray) {
// check for misuse if desired
// if (!Array.isArray(someArray)) {
// throw new TypeError(`getDuplicatedItems requires an Array type, received ${typeof someArray} type.`);
// }
const itemSet = new Set(someArray);
const duplicatedItems = [...itemSet].filter(
(item) => someArray.indexOf(item) !== someArray.lastIndexOf(item)
);
return duplicatedItems;
}
从数组/字符串中获取重复/重复值的最简单方法:
函数getduplicate (param) { Var duplicate = {} For (var I = 0;I < param.length;我+ +){ Var char = param[i] 如果(重复[char]) { 副本(char) + + }其他{ duplicate [char] = 1 } } 返回副本 } console.log (getDuplicates(“aeiouaeiou”)); console.log (getDuplicates((“a”、“e”、“我”、“o”、“u”,“一个”,“e”))); console.log(getduplicate ([1,2,3,4,5,1,1,2,3]));
我试图改善@swilliams的答案,这将返回一个没有重复的数组。
// arrays for testing
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
// ascending order
var sorted_arr = arr.sort(function(a,b){return a-b;});
var arr_length = arr.length;
var results = [];
if(arr_length){
if(arr_length == 1){
results = arr;
}else{
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1] != sorted_arr[i]) {
results.push(sorted_arr[i]);
}
// for last element
if (i == arr.length - 2){
results.push(sorted_arr[i+1]);
}
}
}
}
alert(results);