0

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?

Owenn
  • 638
  • 1
  • 6
  • 23
  • 1
    See [`array.includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes). – Joseph Dec 10 '22 at 17:14
  • Does this answer your question? [Filter array of objects based on another array in javascript](https://stackoverflow.com/questions/46894352/filter-array-of-objects-based-on-another-array-in-javascript) – pilchard Dec 10 '22 at 17:48

2 Answers2

1

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));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0
    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));
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 15 '22 at 06:56