简体   繁体   English

使用javascript从另一个数组中删除数组的元素

[英]Remove elements of an array from another array using javascript

I have two arrays我有两个数组

a[] = [1,2,3,4]
b[] = [1,4]

Need to remove elements of array b from array a.需要从数组 a 中删除数组 b 的元素。

Expected output:预期输出:

 a[] = [1,4]

I would use the filter method:我会使用过滤器方法:

a = a.filter(function (item) {
    return b.indexOf(item) === -1;
});
const array_diff = (a, b) => a.filter(v => !b.includes(v))

如果你想支持 IE

const array_diff = (a, b) => a.filter(v => b.indexOf(v) === -1);

I'm looping over the second array, and checking if the value is in the first array using indexOf If it is I use splice to remove it.我正在遍历第二个数组,并使用indexOf检查值是否在第一个数组中,如果是,我使用splice将其删除。

var a = [1,2,3,4,5];
var b = [3,4,5];

b.forEach(function(val){
  var foundIndex = a.indexOf(val);
  if(foundIndex != -1){
    a.splice(foundIndex, 1);
  }
});

Or或者

var a = [1,2,3,4,5];
var b = [3,4,5];

a = a.filter(x => b.indexOf(x) == -1);

For IE 8,对于 IE 8,

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

Take a look at the jQuery docs for $.grep and $.inArray .查看$.grep$.inArray的 jQuery 文档。

Here's what the code would look like:下面是代码的样子:

var first = [1,2,3,4],
    second = [3,4];

var firstExcludeSecond = $.grep(first, function(ele, ix){ return $.inArray(ele, second) === -1; });

console.log(firstExcludeSecond);

Basically amounts to iterating through the first array ($.grep) and determining if a given value is in the second array ($.inArray).基本上相当于遍历第一个数组 ($.grep) 并确定给定值是否在第二个数组 ($.inArray) 中。 If the value returned from $.inArray is -1, the value from the first array does not exist in the second so we grab it.如果 $.inArray 返回的值为 -1,则第一个数组中的值不存在于第二个数组中,因此我们抓取它。

function myFunction(a, b) {
  return a.filter(item => b.indexOf(item) < 0)
}

console.log(myFunction([1, 2, 3], [1, 2]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM