【发布时间】:2019-06-11 11:24:15
【问题描述】:
我有一个数字数组,其中包含一堆重复项。我需要摆脱它们,所以我把代码:
let dup = arr.filter((elem, pos)=> arr.indexOf(elem) !== pos);
// dup Array contains the duplicate numbers
arr = arr.filter((elem, pos)=> arr.indexOf(elem) == pos);
//arr contains the whole array with duplicates
let i = 0;
let j = 0;
while(i<arr.length){
while(j<dup.length){
if(arr[i] == dup[j]){
arr.splice(i, 1);
//the splice method resets the decrease the index of the array so
i--;
};
j++;
};
i++
}
问题是 if 在第一次匹配后没有运行。所以数组splice 是它找到并停止的第一个重复项。我该如何解决?
【问题讨论】:
-
我很困惑。在您的第二个
filter之后,该数组已经没有重复项。 (并且不需要第一个filter。) -
@ScottSauyet 我认为他想摆脱两个重复的数字。他可以用
arr.filter(x=> dup.indexOf(x) < 0)做到这一点。但他正试图通过一些复杂的循环来删除它 -
@James,哦,好吧,这很有道理。
-
@James 您的回答似乎简单易行。我将用那一行替换我所有的循环。谢谢
标签: javascript arrays loops if-statement