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?

2

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.