My goal is to create a function called removeAll()
that will eliminate all elements of an array with a specific value, rather than based on index.
The challenge arises when any modifications are made to the loop, causing the indexes to shift (which makes achieving the desired outcome difficult). Restarting the loop every time changes are made is not efficient, especially with large arrays.
To address this issue, I have created my own version of the arr.indexOf
function for older IE browsers. Here is the code:
function arrFind(val, arr) {
for (var i = 0, len = arr.length, rtn = -1; i < len; i++) {
if (arr[i] === val) {
return i;
}
}
return -1;
}
Removing elements can be done easily like this:
var myarray = [0, 1, 2, 3, 4];
var tofind = 2;
var stored_index = arrFind(tofind, myarray);
if (stored_index != -1) {
myarray.splice(stored_index, 1);
}
alert(myarray.join(",")); //0,1,3,4
However, as mentioned earlier, complications arise when attempting this within a loop.
Do you have any suggestions for effectively removing array items while iterating through it?