Hi everybody,
This is my first post here ! Today I am reaching out to you because I have a question about arrays in JavaScript.
But first, the context with my algorithm:
function fct1 (Array a, Element e, Boolean b) {
// Some stuff here...
if (b)
fct2 (a);
else
fct2 (a_modified);
// Some more stuff here...
}
where a_modified
is the Array a without the Element e.
Now, my modified array a_modified
is used only once in the code and I can’t permanently modify a
, so I can’t use methods like splice
. I can’t modify fct2
either, so I really have to pass an array.
So I had 2 ideas here, but I am not so satisfied with them:
-
Use a classical
for
loop to create another array stored in a variable. Basically you compare each value of the array withe
and if it’s different you store it in the new array. Here I have to create a variable for something I will use only once, I know it’s not such a big deal but I’d like to avoid it if possible. -
Use the operations on arrays to locate the index of
e
, then concatenate the left and right part of the array. It would be something like that:a.slice(0, a.indexOf(e)).concat(a.slice(a.indexOf(i) + 1));
. Frankly, this is just awful to read.
So here the for
loop might be the best choice, but I was wondering if there wasn’t a way to make things easier. Like a “reversed slice” that would return everything except the sliced element. I know this sounds a bit stupid, but I am a beginner and I have absolutely no idea about the performance of JS Array object methods, nor a good vision of scopes between functions, and it makes me sort of curious .
Thank you very much for your help!