简体   繁体   中英

Matching array of objects with array of values

If I have 2 arrays:

arr1: ["1","2"]
arr2: [{id: 1, color: "green"}, {id: 2, color: "yellow"}, {id: 3, color: "red"}]

And I want to obtain:

result: [{id: 1, color: "green"}, {id: 2, color: "yellow"}]

I am trying with

arr2.filter(
  e => arr1.indexOf(e.id) !== -1
);

But result is empty.

You could use Array.prototype.filter() with Array.prototype.some() method to get the result.

 const arr1 = ['1', '2']; const arr2 = [ { id: 1, color: 'green' }, { id: 2, color: 'yellow' }, { id: 3, color: 'red' }, ]; const ret = arr2.filter((x) => arr1.some((y) => +y === x.id)); console.log(ret);

Another solution using Set Object .

 const arr1 = ['1', '2']; const arr2 = [ { id: 1, color: 'green' }, { id: 2, color: 'yellow' }, { id: 3, color: 'red' }, ]; const set = new Set(arr1); const ret = arr2.filter((x) => set.has(x.id.toString())); console.log(ret);

The problem with your code is that as your inputs have different types( id is a number but arr1 has strings), this arr1.indexOf(e.id) !== -1 will always be false.

Convert one of them to a number like this:

 const arr1 = ["1","2"] const arr2 = [{id: 1, color: "green"}, {id: 2, color: "yellow"}, {id: 3, color: "red"}] const result = arr2.filter(el => arr1.some(aEl => el.id === +aEl)) console.log(result)

Alternatively, you can convert the ids to strings and use your existing code:

 const arr1 = ["1", "2"], arr2 = [{ id: 1, color: "green" }, { id: 2, color: "yellow" }, { id: 3, color: "red" }], result = arr2.filter( e => arr1.indexOf(e.id.toString());== -1 ). console.log(result)

Another solution is may be with .includes() method.

 const arr1 = ["1","2"] const arr2 = [{id: 1, color: "green"}, {id: 2, color: "yellow"}, {id: 3, color: "red"}] const result = arr2.filter(n => arr1.includes(String(n.id))); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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