I working with a really large array and I'm removing few elements from it. By now, every time I want to remove an element without knowing its index, I'm actually doing something like:
const newarr = arr.filter(x => x !== y)
So, everytime I need to remove an element I'm running in O(n) complexity. I think worth creating an structure where I can remove an element from array in O(1) later.
For design purposes, it is an array of references and there aren't repeated elements.
I know I must somehow create an object with index as values and some convenient string as keys, so I can access index in O(1) and remove it using:
const newarr = [...arr.slice(0, i), ...arr.slice(i + 1, arr.length - 1)]
So, how to create this object? Is this a good approach?
O(1), because you still would need to traverse the array if you need to filter items out. Morever, you mention that the original array shouldn't be modified: in your current approach, either slicing either filtering still keeps the "references" to the old array so, if you somehow alter the new array, the old one will be altered as well, which is something you should take care about as well. As a side note, you couldn't do that in C either, not in this way, at least...