返回数组中没有重复的唯一元素 [英] Return unique element that does not have duplicates in an array
问题描述
我试图返回一个只有唯一元素的数组,这些元素在数组中没有重复的特定顺序。
I am trying to return an array with only unique elements that do not have duplicates within the array in no particular order.
[1 ,2,3,3,3,4,4,4,2]
将返回 1
[ hello,卡车,2,卡车,2,卡车]
将返回 hello
到目前为止,我只能使用filter()函数返回唯一元素,但是我不确定该去哪里。
So far I have only been able to return unique elements using the filter() function, but I am not sure where to go.
基本上,如果有重复项,我希望将两个值都从数组中删除。
Basically if there are duplicates I want both values removed from the array.
这听起来很简单,但是我精神上很严重。
This sounds simple enough, but I am having a serious mental hiccup.
下面是我的代码:
function diff(arr1, arr2) {
var newArr = [];
newArr = arr1.concat(arr2);
newArr = newArr.filter(function(elem, index, self) {
return index == self.indexOf(elem);
});
console.log(newArr);
return newArr;
}
diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);
//should return 4
推荐答案
比较 indexOf
和 lastIndexOf
,如果它们相等,则元素没有重复项。将此逻辑使用 .filter
。
Compare the indexOf
and lastIndexOf
, if they are equal then the element has no duplicates. Use .filter
with this logic.
function diff(arr1, arr2) {
return arr1.concat(arr2).filter(function(elem, index, self) {
return self.indexOf(elem)==self.lastIndexOf(elem);
});
}
alert(diff([1, 2, 3, 5], [1, 2, 3, 4, 5]));
这篇关于返回数组中没有重复的唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!