Home > database >  Efficient way to separate an array of objects based on another array
Efficient way to separate an array of objects based on another array

Time:12-11

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?

CodePudding user response:

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));

CodePudding user response:

    const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];
const filterByReference = (arr1, arr2) => {
   let res = [];
   res = arr1.filter(el => {
      return !arr2.find(element => {
         return element.id === el.id;
      });
   });
   return res;
}
console.log(filterByReference(arr1, arr2));
  • Related