1

So I've been trying to remove numbers of an arrayA that are in an arrayB. But if a number is only one time in that arrayB, and more than one time in that arrayA, i want my function to remove only ONE of them.

My function looks like it could work but it doesn't...

the expected output is : 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 Answers3

6

A single loop is enough. Loop arrayB and remove the found element from arrayA. indexOf will always stop at the first hit, which makes it fairly simple:

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);
baao
  • 71,625
  • 17
  • 143
  • 203
1

You can loop through arrayB and remove the same value in 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);
Faly
  • 13,291
  • 2
  • 19
  • 37
  • 1
    There's no reason for using `findIndex`, and no reason for using complex destructuring. – baao May 11 '18 at 13:16
1

You could take a hash table and count down the occurence of the not wanted items.

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]--));

For sorted arrays, as given, you could use an index as closure over the 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)));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392