所以我一直在尝试删除 arrayB 中的 arrayA 的数字。但是如果一个数字在那个 arrayB 中只有一次,而在那个 arrayA 中不止一次,我希望我的函数只删除其中一个。
我的函数看起来可以工作,但实际上没有...
预期的输出是:1,3,3,4,5
let arrayA = [1,1,2,3,3,3,4,4,5]
let arrayB = [1,2,3,4]
function remove(arrayB,arrayA){
//newarray is the result array i want to get
let newarray = [];
//counter will controll if a number is more than one time in my arrayA
let counter = [];
arrayA.forEach(function(n){
//if a number of my arrayA is not in my arrayB
if(arrayB.indexOf(n) == -1){
newarray.push(n);
}
//if a number of my arrayB is only one time in my arrayA
else if(a.indexOf(n) == a.lastIndexOf(n)){
}
//if a number is more than one time but its the first one we meet
else if(a.indexOf(n) !== a.lastIndexOf(n) && counter.includes(n) == false){
//push it into the counter array so we'll know we already had this number
counter.push(n)
}
// if it's the second time we have to keep it and get it in the newarray
else {
newarray.push(n);
}
})
document.write(newarray)
}
最佳答案
一个循环就足够了。循环 arrayB 并从 arrayA 中删除找到的元素。 indexOf
将始终在第一次命中时停止,这使其相当简单:
let arrayA = [1,1,2,3,3,3,4,4,5];
let arrayB = [1,2,3,4];
arrayB.forEach(e => arrayA.splice(arrayA.indexOf(e), 1));
console.log(arrayA);
关于javascript:如果数组中的值在另一个数组中,则只删除一次该值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50292994/