Reputation: 1758
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.
Upvotes: 0
Views: 62
Reputation: 3302
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);
Upvotes: 2
Reputation: 776
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);
Upvotes: 0
Reputation: 10662
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)
Upvotes: 2