0

I wrote this code to remove all 2 and 3 from the array and wanted to have this result:

destroyer([1, 2, 3, 1, 2, 3], 2, 3); // returns [1, 1]

but instead the result is:

destroyer([1, 2, 3, 1, 2, 3], 2, 3); // returns [1, 2, 1, 3]

This is function code:

function destroyer(arr) {
  var a = Array.prototype.slice.call(arguments);
  var b = a[0];

  for (var i = 1; i < a.length; i++) {
    if (b.indexOf(a[i]) !== -1) {
      b.splice(a[i], 1);
    }
  }

  return b;
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
lolbas
  • 794
  • 1
  • 9
  • 34
Sur Khosh
  • 115
  • 1
  • 8

3 Answers3

1

You can do this using .filters

b.filter(el => !a.includes(el));

Check the complete code below:

function destroyer(a, ...b) {
  a = a.filter(el => !b.includes(el));
  console.log(a);
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);
void
  • 36,090
  • 8
  • 62
  • 107
0

Try this

function destroyer(arr) {
  var args = Array.prototype.slice.call(arguments);
  var a = args[0];
  var b = args.slice(1);

  for (var i=0; i < a.length; i++) {
    if (b.indexOf(a[i]) !== -1) {
      a.splice(i,1);
      i--;
    }
  }
  return a;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);
Pavan Bahuguni
  • 1,947
  • 1
  • 15
  • 21
0

This approach with destroyer2() is much simpler and faster with benchmark

function destroyer(arr) {
  var a = Array.prototype.slice.call(arguments);
  var b = a.splice(0,1)[0];
  
  b = b.filter(el => !a.includes(el));
  console.log(b);
}

console.time('destroyer1');
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
console.timeEnd('destroyer1');

// This is much faster than the previous example
function destroyer2(inputs, removables) {
  var len = inputs.length;
  while(len--) {
    if(removables.indexOf(inputs[len]) !== -1) {
      inputs.splice(len, 1); // Remove at specific index if found
    }
  }
  return inputs;
}

console.time('destroyer2');
console.log(destroyer2([1, 2, 3, 1, 2, 3], [2, 3]));
console.timeEnd('destroyer2');
CodeLover
  • 571
  • 2
  • 11