0

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)
}
3
  • 2
    It's not at the same index. You need to use Array.find() instead. Or you first create a Set of ids to remove, then check is the set has() the id. Commented Aug 8, 2022 at 12:32
  • You probably don't need the for loop at all if you're using filter. Commented Aug 8, 2022 at 12:33
  • @ChrisG evolutionxbox can you post answer so i can get idea Commented Aug 8, 2022 at 12:35

2 Answers 2

3

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

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

Comments

0

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

1 Comment

although this solves the problem it does the map call in every iteraton of the filter

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.