Home > Net >  remove 2 common array item javascript
remove 2 common array item javascript

Time:08-08

I have 2 arrays

let arryOne =
[
  {
   'catRefId' : "200531-2"
  },
  {
   'catRefId' : "201425-1"
 },
 {
   'catRefId' : "201423-1"
 },
 ]

let arryTwo =
 [
   {

    'removeId' : "200531-2"
   },
   {
    'removeId' : "201425-1"
   },
  ]

I tried below code but not working

let _finalArray = [];
for (let index = 0; index < arryOne.length; index  ) {
_finalArray = arryOne.filter(obj => obj.catRefId === arryTwo[index].removeId)
}

CodePudding user response:

Here's an approach using Set

let arryTwo = [{ removeId: '200531-2' }, { removeId: '201425-1'}];
let arryOne = [{ catRefId: '200531-2' }, { catRefId: '201425-1'},{ catRefId: '201423-1' }];

const idsToRemove = new Set(arryTwo.map(({ removeId }) => removeId));

const _finalArray = arryOne.filter((item) => !idsToRemove.has(item.catRefId));
console.log(_finalArray);

CodePudding user response:

This is a possible solution: First we extract the Ids from the second array. Then we filter all matching references.

What's left is all references not present in arryTwo.

let _finalArray = [];
_finalArray = arryOne.filter(obj => !arryTwo.map(obj => obj.removeId).includes(obj.catRefId));
  • Related