javascript:只删除一个数组中的值,如果它在另一个数组中

时间:2018-05-11 13:04:43

标签: javascript arrays

所以我一直在尝试删除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)
  }

3 个答案:

答案 0 :(得分:6)

单循环就足够了。循环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);




答案 1 :(得分:1)

您可以遍历arrayB并删除arrayA中的相同值:



var arrayA = [1,1,2,3,3,3,4,4,5];
var arrayB = [1,2,3,4];
arrayB.forEach(b => {
    var index = arrayA.findIndex(a => a === b);
    arrayA = [ ...arrayA.slice(0, index), ...arrayA.slice(index + 1)];
});
console.log(arrayA);




答案 2 :(得分:1)

您可以使用哈希表并倒计时不想要的项目。



var arrayA = [1, 1, 2, 3, 3, 3, 4, 4, 5],
    arrayB = [1, 2, 3, 4],
    hash = arrayB.reduce((o, v) => (o[v] = (o[v] || 0) + 1, o), Object.create(null));
    
console.log(arrayA.filter(v => !hash[v] || !hash[v]--));




对于已排序的数组,您可以使用索引作为arrayB上的闭包。



var arrayA = [1, 1, 2, 3, 3, 3, 4, 4, 5],
    arrayB = [1, 2, 3, 4];
    
console.log(arrayA.filter((i => v => v !== arrayB[i] || !++i)(0)));