Sco*_*ers 397 javascript arrays
我需要检查一个JavaScript数组,看看是否有任何重复的值.最简单的方法是什么?我只需要找到重复的值是什么 - 我实际上并不需要它们的索引或重复它们的次数.
我知道我可以遍历数组并检查匹配的所有其他值,但似乎应该有一个更简单的方法.有任何想法吗?谢谢!
swi*_*ams 282
您可以对数组进行排序,然后运行它,然后查看下一个(或上一个)索引是否与当前索引相同.假设您的排序算法很好,这应该小于O(n 2):
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var sorted_arr = arr.slice().sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
// (we use slice to clone the array so the
// original array won't be modified)
var results = [];
for (var i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
console.log(results);Run Code Online (Sandbox Code Playgroud)
rap*_*ria 204
如果您想要重复删除重复项,请尝试以下解决方案:
function eliminateDuplicates(arr) {
var i,
len = arr.length,
out = [],
obj = {};
for (i = 0; i < len; i++) {
obj[arr[i]] = 0;
}
for (i in obj) {
out.push(i);
}
return out;
}
Run Code Online (Sandbox Code Playgroud)
资料来源:http: //dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/
Chr*_*ren 160
这是我从重复的线程(!)得到的答案:
厌倦了看到所有使用for循环或jQuery的坏例子.Javascript现在拥有完美的工具:排序,映射和缩小.
var names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']
var uniq = names
.map((name) => {
return {
count: 1,
name: name
}
})
.reduce((a, b) => {
a[b.name] = (a[b.name] || 0) + b.count
return a
}, {})
var duplicates = Object.keys(uniq).filter((a) => uniq[a] > 1)
console.log(duplicates) // [ 'Nancy' ]Run Code Online (Sandbox Code Playgroud)
@ Dmytro-Laptin指出要删除一些代码.这是相同代码的更紧凑版本.使用一些ES6技巧和更高阶函数:
const names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']
const count = names =>
names.reduce((a, b) => ({ ...a,
[b]: (a[b] || 0) + 1
}), {}) // don't forget to initialize the accumulator
const duplicates = dict =>
Object.keys(dict).filter((a) => dict[a] > 1)
console.log(count(names)) // { Mike: 1, Matt: 1, Nancy: 2, Adam: 1, Jenny: 1, Carl: 1 }
console.log(duplicates(count(names))) // [ 'Nancy' ]Run Code Online (Sandbox Code Playgroud)
var names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']
var uniq = names
.map((name) => {
return {
count: 1,
name: name
}
})
.reduce((a, b) => {
a[b.name] = (a[b.name] || 0) + b.count
return a
}, {})
var duplicates = Object.keys(uniq).filter((a) => uniq[a] > 1)
console.log(duplicates) // [ 'Nancy' ]Run Code Online (Sandbox Code Playgroud)
flu*_*flu 53
这应该是在数组中实际查找重复值的最短方法之一.正如OP特别要求的那样,这不会删除重复但会找到它们.
var input = [1, 2, 3, 1, 3, 1];
var duplicates = input.reduce(function(acc, el, i, arr) {
if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); return acc;
}, []);
document.write(duplicates); // = 1,3 (actual array == [1, 3])Run Code Online (Sandbox Code Playgroud)
这不需要排序或任何第三方框架.它也不需要手动循环.它适用于每个值indexOf()(或更清晰:严格的比较运算符)支持.
由于reduce()和indexOf(),它至少需要IE 9.
kar*_*m79 30
您可以添加此功能,或调整它并将其添加到Javascript的Array原型中:
Array.prototype.unique = function () {
var r = new Array();
o:for(var i = 0, n = this.length; i < n; i++)
{
for(var x = 0, y = r.length; x < y; x++)
{
if(r[x]==this[i])
{
alert('this is a DUPE!');
continue o;
}
}
r[r.length] = this[i];
}
return r;
}
var arr = [1,2,2,3,3,4,5,6,2,3,7,8,5,9];
var unique = arr.unique();
alert(unique);
Run Code Online (Sandbox Code Playgroud)
小智 27
更新:以下使用优化的组合策略.它优化了原始查找以受益于散列O(1)查找时间(unique在基元数组上运行是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;
}();
Run Code Online (Sandbox Code Playgroud)
如果您有可用的ES6集合,则可以使用更简单且速度更快的版本.(这里是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;
}
});
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*ley 17
这应该得到你想要的,只是重复.
function find_duplicates(arr) {
var len=arr.length,
out=[],
counts={};
for (var i=0;i<len;i++) {
var item = arr[i];
counts[item] = counts[item] >= 1 ? counts[item] + 1 : 1;
if (counts[item] === 2) {
out.push(item);
}
}
return out;
}
find_duplicates(['one',2,3,4,4,4,5,6,7,7,7,'pig','one']); // -> ['one',4,7] in no particular order.
Run Code Online (Sandbox Code Playgroud)
Ang*_*ott 17
var a = ["a","a","b","c","c"];
a.filter(function(value,index,self){ return (self.indexOf(value) !== index )})
Run Code Online (Sandbox Code Playgroud)
att*_*ian 15
最简单、最快的方法是使用Set对象:
const numbers = [1, 2, 3, 2, 4, 5, 5, 6];
const set = new Set(numbers);
const duplicates = numbers.filter(item => {
if (set.has(item)) {
set.delete(item);
return false;
} else {
return true;
}
});
// OR more concisely
const duplicates = numbers.filter(item => !set.delete(item));
console.log(duplicates);
// [ 2, 5 ]
Run Code Online (Sandbox Code Playgroud)
Lau*_*yot 14
当您只需检查此问题中没有重复项时,您可以使用以下filter()方法:
[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i) // [2, 4]
Run Code Online (Sandbox Code Playgroud)
请注意,这every()不适用于IE 8及更低版本.
我使用every()它是因为它可能比在索引顺序中进行的filter()函数回调更有效every(),但是没有证明.
在CoffeeScript中我使用这个:
[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) === i) // [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
小智 13
使用underscore.js
function hasDuplicate(arr){
return (arr.length != _.uniq(arr).length);
}
Run Code Online (Sandbox Code Playgroud)
一个班轮简单的方法
var arr = [9,1,2,4,3,4,9]
console.log(arr.filter((ele,indx)=>indx!==arr.indexOf(ele))) //get the duplicates
console.log(arr.filter((ele,indx)=>indx===arr.indexOf(ele))) //remove the duplicatesRun Code Online (Sandbox Code Playgroud)
这是我的简单和一线解决方案.
它首先搜索不是唯一的元素,然后使用Set使找到的数组唯一.
所以我们最后有一系列重复.
var array = [1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 7, 8, 5, 22, 1, 2, 511, 12, 50, 22];
console.log([...new Set(
array.filter((value, index, self) => self.indexOf(value) !== index))]
);Run Code Online (Sandbox Code Playgroud)
这是我能想到的最简单的解决方案:
const arr = [-1, 2, 2, 2, 0, 0, 0, 500, -1, 'a', 'a', 'a']
const filtered = arr.filter((el, index) => arr.indexOf(el) !== index)
// => filtered = [ 2, 2, 0, 0, -1, 'a', 'a' ]
const duplicates = [...new Set(filtered)]
console.log(duplicates)
// => [ 2, 0, -1, 'a' ]Run Code Online (Sandbox Code Playgroud)
就是这样。
笔记:
它适用于任何数字,包括0、字符串和负数,例如-1-
相关问题: 获取 JavaScript 数组中的所有唯一值(删除重复项)
arr保留原始数组(filter返回新数组而不是修改原始数组)
该filtered数组包含所有重复项;它还可以包含 1 个以上的相同值(例如,我们这里的过滤数组是[ 2, 2, 0, 0, -1, 'a', 'a' ])
如果你想获得仅是重复的值(你不希望有相同值的多个副本),可以使用[...new Set(filtered)](ES6都有一个对象集可存储唯一的值)
希望这可以帮助。
Array.prototype.unique = function () {
var arr = this.sort(), i; // input must be sorted for this to work
for( i=arr.length; i--; )
arr[i] === arr[i-1] && arr.splice(i,1); // remove duplicate item
return arr;
}
var arr = [1,2,2,3,3,4,5,6,2,3,7,8,5,9],
arr2 = [1,2,511,12,50],
arr3 = [22],
unique = arr.concat(arr2, arr3).unique();
console.log(unique); // [22, 50, 12, 511, 2, 1, 9, 5, 8, 7, 3, 6, 4]
Run Code Online (Sandbox Code Playgroud)
if (!Array.prototype.indexOf){
Array.prototype.indexOf = function(elt /*, from*/){
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++){
if (from in this && this[from] === elt)
return from;
}
return -1;
};
}
Run Code Online (Sandbox Code Playgroud)
if( $.inArray(this[i], arr) == -1 )
Run Code Online (Sandbox Code Playgroud)
var arr = [1,2,2,3,3,4,5,6,2,3,7,8,5,22],
arr2 = [1,2,511,12,50],
arr3 = [22],
unique;
// Combine all the arrays to a single one
unique = arr.concat(arr2, arr3);
// create a new (dirty) Array with only the unique items
unique = unique.map((item,i) => unique.includes(item, i+1) ? item : '' )
// Cleanup - remove duplicate & empty items items
unique = [...new Set(unique)].filter(n => n);
console.log(unique);Run Code Online (Sandbox Code Playgroud)
而不是添加'Array.prototype.indexOf'
var a = [324,3,32,5,52,2100,1,20,2,3,3,2,2,2,1,1,1].sort();
a.filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});
Run Code Online (Sandbox Code Playgroud)
或者当添加到Array的prototyp.chain时
//copy and paste: without error handling
Array.prototype.unique =
function(){return this.sort().filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});}
Run Code Online (Sandbox Code Playgroud)
见这里:https://gist.github.com/1305056
使用ES6对象分解和减少的快速而优雅的方式
它以O(n)运行(在数组上进行1次迭代),并且不会重复出现超过2次的值
const arr = ['hi', 'hi', 'hi', 'bye', 'bye', 'asd']
const {
dup
} = arr.reduce(
(acc, curr) => {
acc.items[curr] = acc.items[curr] ? acc.items[curr] += 1 : 1
if (acc.items[curr] === 2) acc.dup.push(curr)
return acc
}, {
items: {},
dup: []
},
)
console.log(dup)
// ['hi', 'bye']Run Code Online (Sandbox Code Playgroud)
This is my proposal (ES6):
let a = [1, 2, 3, 4, 2, 2, 4, 1, 5, 6]
let b = [...new Set(a.sort().filter((o, i) => o !== undefined && a[i + 1] !== undefined && o === a[i + 1]))]
// b is now [1, 2, 4]
Run Code Online (Sandbox Code Playgroud)
最短的香草JS:
[1,1,2,2,2,3].filter((v,i,a) => a.indexOf(v) !== i) // [1, 2, 2]
Run Code Online (Sandbox Code Playgroud)
小智 5
You can use filter method and indexOf() to get all the duplicate values
function duplicate(arr) {
return duplicateArray = arr.filter((item, index) => arr.indexOf(item) !== index)
}
Run Code Online (Sandbox Code Playgroud)
arr.indexOf(item) will always return the first index at which a given element can be found
| 归档时间: |
|
| 查看次数: |
545664 次 |
| 最近记录: |