For example I have an array of objects and an array as such:
const arrayObj = [
{
id: 1,
name: "user1",
},
{
id: 2,
name: "user2",
},
{
id: 3,
name: "user3",
},
]
const array = ["user1", "user2"]
How is it I'm able to separate arrayObj
into two arrays based on array
as such:
const array1 = [
{
id: 1,
name: "user1",
},
{
id: 2,
name: "user2",
},
]
const array2 = [
{
id: 3,
name: "user3",
},
]
I was thinking maybe something like this:
const filteredArray = arrayObj.filter((el) => {
return array.some((f) => {
return f === el.name;
});
});
But is there a more efficient / quicker way?
Unless the arrays you're dealing with are huge, your current code is fine.
If the arrays are huge and the current code is too slow, put the names into a Set and check Set.has
instead of Array.some
- Set.has
is much faster when there are many elements in the Set.
const userSet = new Set(array);
const usersInUserSet = arrayObj.filter(user => userSet.has(user.name));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments