Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Efficient way to separate an array of objects based on another array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const filteredArray = arrayObj.filter((el) => {
  return array.some((f) => {
    return f === el.name;
  });
});

But is there a more efficient / quicker way?

>Solution :

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.someSet.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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading