Javascript-从数组中删除唯一元素 [英] Javascript - Remove Unique Elements from Array
问题描述
我想知道如何从数组中删除唯一元素.例如:
I am wondering how one would go about removing unique elements from an array. For example:
var arr = [1、2、2、4、4]
将返回 [2、2、4、4]
.因为所有元素都是唯一的,所以 [1、2、3]
将返回 []
.
var arr = [1, 2, 2, 4, 4]
would return [2, 2, 4, 4]
. Where [1, 2, 3]
would return []
because all elements are unique.
我相信我需要检查数组中的每个其他元素,但是我不确定该怎么做.
I believe I need to check each element with every other element in the array, but I'm not sure how to go about this.
谢谢!
推荐答案
使用ES6,您可以使用 Array#forEach
.
With ES6, you could use a Array#map
and count the values with Array#forEach
.
以后使用 Array#filter
并检查计数.
Later use Array#filter
and check the count.
如果大于 1
,则返回 true
(在结果集中包含该项),否则返回 false
(在结果集).
If greater than 1
return true
(include the item in the result set), otherwise return false
(do not include item in the result set).
function getNotUnique(array) {
var map = new Map();
array.forEach(a => map.set(a, (map.get(a) || 0) + 1));
return array.filter(a => map.get(a) > 1);
}
console.log(getNotUnique([1, 2, 2, 4, 4]));
console.log(getNotUnique([1, 2, 3] ));
这篇关于Javascript-从数组中删除唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!