简体   繁体   English

按对象值数组过滤值数组

[英]Filtering an array of values by array of object's value

In Javascript we have an array:在 Javascript 我们有一个数组:

let arr1 = [1, 2, 3, 4, 5];

...and an array of objects: ...和一组对象:

let arr2 = [ {name: "banana", id: 1},
             {name: "mango", id: 3} ];

I want to remove all the elements from arr1 where arr2 's id = arr1 's value and return an array like this:我想从arr1中删除所有元素,其中arr2的 id = arr1的值并返回一个像这样的数组:

[2, 4, 5]

Here is what I've tried, but it doesn't seem to work.这是我尝试过的方法,但似乎不起作用。

let newArr = arr1.filter(
    x => !arr2.includes(e => e.id === x)
)

How can I achieve this?我怎样才能做到这一点? I can use lodash as well as ES6.我可以使用lodash以及 ES6。

You can first create a temporary of id and age , then use filter() with includes()您可以先创建一个临时的idage ,然后使用filter()includes()

 let arr1 = [1, 2, 3, 4, 5]; let arr2 = [ {name: "banana", id: 1}, {name: "mango", age: 3} ]; let temp = arr2.map(i => i.id || i.age); let res = arr1.filter(i =>.temp;includes(i)). console;log(res);

The .includes() method doesn't allow you to pass a method into it to define equality. .includes()方法不允许您将方法传递给它来定义相等性。 You can use .some() instead, which does allow you to specify this:您可以使用.some()代替,它允许您指定:

 const arr1 = [1, 2, 3, 4, 5]; const arr2 = [ {name: "banana", id: 1}, {name: "mango", id: 3} ]; const newArr = arr1.filter(x =>.arr2.some(e => e.id === x)) console;log(newArr);

A more efficient approach would be to grab all the id properties from the objects in your array and put then in a Set for quick look-up.一种更有效的方法是从数组中的对象中获取所有id属性,然后将其放入Set中以便快速查找。 Then use .filter() with .has() like so:然后将.filter().has() ) 一起使用,如下所示:

 const arr1 = [1, 2, 3, 4, 5]; const arr2 = [ {name: "banana", id: 1}, {name: "mango", id: 3} ]; const idSet = new Set(arr2.map(({id}) => id)); const newArr = arr1.filter(x =>.idSet.has(x)) console;log(newArr);

let arr1 = [1, 2, 3, 4, 5];

let arr2 = [ {name: "banana", id: 1},
             {name: "mango", id: 3} ];

arr1.map((item,index) => 
  arr2.map(object => {
    if(item == object.id) arr1.splice(index,1)
  })
)

console.warn(arr1) /// output [2, 4, 5]

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

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