-1

I have two array of objects as below:

1st array:

const arr1 = [
  {
    name: 'Jackson',
    email: '[email protected]',
    _id: '634793ba0d09e246dbed7988'
  },
  {
    name: 'Carlson',
    email: '[email protected]',
    _id: '633c33880d09e246dbed6e3f'
  }
]

2nd array:

const arr2 = [
  {
    name: 'Samson',
    email: '[email protected]',
    _id: '"634e878db465120ccc6ca81f'
  },
  {
    name: 'Jennifer',
    email: '[email protected]',
    _id: '633c339c0d09e246dbed6eeb'
  },
  {
    name: 'Carlson',
    email: '[email protected]',
    _id: '633c33880d09e246dbed6e3f'
  }
]

Now, I want to filter my 2nd array based on the _id. If same ids, then remove that object from the array.

Expected result should be:

[
  {
    name: 'Samson',
    email: '[email protected]',
    _id: '"634e878db465120ccc6ca81f'
  },
  {
    name: 'Jennifer',
    email: '[email protected]',
    _id: '633c339c0d09e246dbed6eeb'
  }
]

Below is my approach:

this.finalArray = this.arr2.filter(item => {
  this.arr1.forEach(other=> {
    if (item._id !== other._id) {
      return item;
    }
  });
});

But I'm getting an empty array. How can I achieve that?

1
  • this can be done without nested loop const set1 = new Set(); arr1.forEach(elem=>set1.add(elem._id)); const filterArr = arr2.reduce((acc,curr)=>{ if(!set1.has(curr._id)){ acc.push(curr) } return acc; },[]); console.log(filterArr) Commented Oct 18, 2022 at 12:54

1 Answer 1

1

const arr1 = [
  {
    name: 'Jackson',
    email: '[email protected]',
    _id: '634793ba0d09e246dbed7988'
  },
  {
    name: 'Carlson',
    email: '[email protected]',
    _id: '633c33880d09e246dbed6e3f'
  }
]

const arr2 = [
  {
    name: 'Samson',
    email: '[email protected]',
    _id: '"634e878db465120ccc6ca81f'
  },
  {
    name: 'Jennifer',
    email: '[email protected]',
    _id: '633c339c0d09e246dbed6eeb'
  },
  {
    name: 'Carlson',
    email: '[email protected]',
    _id: '633c33880d09e246dbed6e3f'
  }
]

const result = arr2.filter(item => !arr1.find(obj => obj._id === item._id));
console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.