如何从初始数组中删除与这些参数具有相同值的所有元素?

时间:2018-02-21 05:34:54

标签: javascript

我编写了此代码以从数组中删除所有23,并希望获得此结果:

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

但结果却是:

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

这是功能代码:



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));
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

您可以使用.filters

执行此操作

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

检查以下完整代码:

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

destroyer([1, 2, 3, 1, 2, 3], 2, 3);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

使用基准

destroyer2()的这种方法更简单,更快捷

&#13;
&#13;
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');
&#13;
&#13;
&#13;