Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple items of an array by value?

I am trying to make a removeAll() function, which will remove all elements of an array with that particular value (not index).

The tricky part comes when we make any change to the loop, the indexes tend to move around (making it very hard to make it work like we want) and, restarting the loop every time we make changes is very inefficient on big arrays.

So far, I wrote my own arr.indexOf function (for older IE support), it looks like this:

function arrFind(val, arr) {
    for (var i = 0, len = arr.length, rtn = -1; i < len; i++) {
        if (arr[i] === val) {
            return i;
        }
    }
    return -1;
}

It is easy to remove elements 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 I pointed out earlier, when doing this while looping, we get in trouble.

Any ideas on how to properly remove array items while looping through it?

like image 953
ajax333221 Avatar asked Feb 15 '12 03:02

ajax333221


People also ask

How do I remove an item from an array by value?

To remove an object from an array by its value:Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.


2 Answers

Loop in reverse order or build a new array with the items that are not to be removed.

like image 168
epascarello Avatar answered Oct 12 '22 23:10

epascarello


Every new browser has an Array filter method:

var myarray=[0,1,2,3,4];
var removal=2;
var newarray=myarray.filter(function(itm){return itm!==removal});
like image 25
kennebec Avatar answered Oct 13 '22 01:10

kennebec