Anji
Anji

Reputation: 67

Remove Array Json object elements

Here I have two arrays

var arry1 = [{id:1,name:"muni"},{id:2,name:"Anji"}, {id:3,name:"vinod"},{id:4,name:"anil"}];

var arry2 = [{id:3},{id:1}];

I want the following results

arry1= [{id:2,name:"Anji"},{id:4,name:"anil"}]

Should be remove second selected elements in first array

Upvotes: 0

Views: 96

Answers (3)

Terry Lennox
Terry Lennox

Reputation: 30685

You can use Array.filter to remove any element that is present in arry2. We can create a Set of id elements to filter out, this will be more efficient for larger arrays:

var arry1 = [{id:1,name:"muni"},{id:2,name:"Anji"}, {id:3,name:"vinod"},{id:4,name:"anil"}];
var arry2 = [{id:3},{id:1}];

// Filter out any elements in arry1 that are also present in arry2, first create a Set of IDs to filter
const idsToFilter = new Set(arry2.map(el => el.id));
const result = arry1.filter(el => !idsToFilter.has(el.id));

console.log("Result:", result)

Upvotes: 1

Anku Singh
Anku Singh

Reputation: 954

Try this it will work, here filter will filter out only those array element which doesn't exist in arry2

var myArray = arry1.filter(ar => !arry2.find(el => (el.id === ar.id) ))

Upvotes: 0

fravolt
fravolt

Reputation: 3001

While removing from an array, you should iterate backwards over it.

for (let i = arry1.length - 1; i >=0; i--) {
  ...
}

This ensures that no elements are skipped after an element is removed. See also this other question for more info on this.

Now for each element of arry1 we want to check whether it should be removed.

let idsToRemove = arry2.map(e => e.id); // [3, 1]

for (let i = arry1.length - 1; i >=0; i--) {
  if (idsToRemove.includes(arry1[i].id) {
    // it should be removed
    arry1.splice(i, 1);
  }
}

Something like the above should then work for your problem. For easier understanding of the code, I first mapped arry2 to only the IDs, but of course you can also use another loop to see whether there is a match. The most important take-away is that to safely remove from an array while iterating it, you need to iterate from the last to the first element.

Upvotes: 0

Related Questions