Jake
Jake

Reputation: 26137

Angular - Remove elements in array of objects based on whose index matches a value in another array

I have an array of Indices and an array of objects:

let indices = [1,3,5]
let objArray = [{name: "John"}, {name: "Jack"}, {name: "Steve"}, {name: "Margot"},
                {name: "Tim"}, {name: "Elma"}]

I would like to modify objArray such that if the index of these objects match the values in the indices array, those entries should be deleted in the resulting array.

Ex: Modified objArray should be: [{name: "John"}, {name: "Steve"}, {name: "Tim"}] because 2, 4 and 6 elements matched the index for the values in the indices array.

I tried to do this, but indexOf is always returning -1

for(let i=0;i<indices.length;i++) {
  if(objArray.indexOf(indices[i]) > -1) {
        delete objArray[indices[i]];
      }
}

Upvotes: 1

Views: 45

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371168

Don't delete with arrays, use the semantic .filter to filter the array by whether the index being iterated over is in the indicies to exclude:

let indices = [1,3,5]
let objArray = [{name: "John"}, {name: "Jack"}, {name: "Steve"}, {name: "Margot"},
                {name: "Tim"}, {name: "Elma"}]
const result = objArray.filter((_, i) => !indices.includes(i));
console.log(result);

Upvotes: 2

Related Questions