0

I'm trying to remove elements in an array using a list of IDs to remove.

const dataArray = [];
const idsToRemove = new Set();

for (let i=0; i<10; i++) {
  dataArray.push({id: "myID" + i, value: i});
}

for (let i=0; i<10; i+=2) {
  idsToRemove.add("myID" + i);
}

const newArray = dataArray.filter(obj => !idsToRemove.has(obj.id));
console.log(newArray);

Result:

{id:"myID1", value:1}, {id:"myID3",value:3}, {id:"myID5", value:5}, {id:"myID7", value:7}, {id:"myID9",value:9}

Is this an ideal solution? Or would there be a more performant solution than this?

ADDED: Would there be a way to avoid making a newArray but just directly remove elements from dataArray?

2
  • The solution seems ideal to me.... also we can use Map instead of Set to store idsToRemove so that it's time complexity would improve... Commented May 3, 2020 at 5:29
  • I found two solutions that are faster than mine: jsben.ch/ld9op Commented May 3, 2020 at 7:05

2 Answers 2

1

You can save some computational effort by preparing the remove list as an object with the target IDs as key:

let dataArray=[];
for (let i=0; i<10; i++) {
  dataArray.push({id: "myID" + i, value: i});
}
let idsToRemove={};
for (i=0;i<10;i+=2) idsToRemove["myID"+i]=1;
var filtered=dataArray.filter(o=>!idsToRemove[o.id]);   
console.log(filtered);

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

Comments

1

Here's a modern way of coding this (not performance oriented):

const dataArray = new Array(10).fill(0).map((item, idx) => idx);

const idsToRemove = new Set(dataArray.filter(i => i % 2 === 0));

const newArray = dataArray.filter(i => !idsToRemove.has(i)).map(i => ({id: `myID${i}`, value: i}));

console.log(newArray);

2 Comments

How does this not have loops? You have fill, map and filter all of which are shorthand for loops.
@Nick - Behind the scenes it does loop obviously. But this is a more modern approach of coding these stuff today if you aren't performance oriented.

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.