1

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]];
      }
}

1 Answer 1

2

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

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

Comments

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.