I have an initial array of objects and 2 arrays of ids as following:
const arr = [
{ id: 1, name: "John" },
{ id: 7, name: "Alice" },
{ id: 10, name: "Ken" },
{ id: 5, name: "Bob" },
{ id: 2, name: "Kevin" },
{ id: 6, name: "Tony" },
{ id: 3, name: "Harry" },
{ id: 4, name: "Kyle" },
{ id: 8, name: "Jane" },
{ id: 9, name: "Sam" },
];
const list1 = [1, 4, 2];
const list2 = [3, 8, 9, 10];
What I want is 2 new sub arrays of arr
which include the objects having the respective id in list1
and list2
. Notice that the order of objects of two new sub arrays must be as the same order of ids in list1
and list2
.
I have tried the below way, it works but may not be effective with a large number of items in arr
:
const subArr1 = [];
const subArr2 = [];
list1.forEach((id) => {
const idx = arr.findIndex((item) => item.id === id);
if (idx !== -1 && subArr1.findIndex((item) => item.id === id) === -1) {
subArr1.push(arr[idx]);
}
});
list2.forEach((id) => {
const idx = arr.findIndex((item) => item.id === id);
if (idx !== -1 && subArr2.findIndex((item) => item.id === id) === -1) {
subArr2.push(arr[idx]);
}
});
/* Result:
subArr1 = [
{ id: 1, name: "John" },
{ id: 4, name: "Kyle" },
{ id: 2, name: "Kevin" },
];
subArr2 = [
{ id: 3, name: "Harry" },
{ id: 8, name: "Jane" },
{ id: 9, name: "Sam" },
{ id: 10, name: "Ken" },
];
*/
Beside my idea, is there any better solution?
Updated:
The Array.prototype.filter()
and Array.prototype.includes()
works to create 2 new sub arrays but the order also should be the same as order of ids in list1
and list2
4
Answers
You can try using
Array.prototype.map()
and
Array.prototype.find()
In the above solution, the
map()
is used onlist1
andlist2
to iterate over each ID. Then, thefind()
is used to find the corresponding item inarr
based on the current ID. This maintains the order of the IDs in the resultingsubArr1
andsubArr2
.Here’s a solution:
The
.filter(e => e)
is optional if you don’t wantundefined
in your list when the id is not found.