Remove entry from array using another array

2020-04-18 09:00发布

Not sure how do to this, so any help is greatly appreciated

Say I have :

const array1 = [1, 1, 2, 3, 4];
const array2 = [1, 2];

Desired output

const result = [1, 3, 4];

I wish to compare array1 and array2 and for each entry in array2, remove the equivalent from array1. So if I have 3 of 1 in array1 and 1 of 1 in array2, the resulting array should have 2 of 1.

Working on a project that has both jquery and underscore.js if that makes anything easier.

7条回答
我想做一个坏孩纸
2楼-- · 2020-04-18 09:38

var array1 = [1, 1, 2, 3, 4],
  array2 = [1, 2],
  result = array1.slice(0);

array2.forEach(function(element) {
  var index = result.indexOf(element)
  if (index >= 0) {
    result.splice(index, 1)
  }
})
console.log(result)

查看更多
登录 后发表回答