Remove items from array with splice in for loop [duplicate] Remove items from array with splice in for loop [duplicate] arrays arrays

Remove items from array with splice in for loop [duplicate]


Solution 1

You can loop backwards, with something like the following:

var searchInput, i;searchInput = ["this", "is", "a", "test"];i = searchInput.length;while (i--) {    if (searchInput[i].length < 4) {        searchInput.splice(i, 1);    }}

DEMO: http://jsfiddle.net/KXMeR/

This is because iterating incrementally through the array, when you splice it, the array is modified in place, so the items are "shifted" and you end up skipping the iteration of some. Looping backwards (with a while or even a for loop) fixes this because you're not looping in the direction you're splicing.


Solution 2

At the same time, it's usually faster to generate a new array instead of modifying one in place. Here's an example:

var searchInput, newSearchInput, i, j, cur;searchInput = ["this", "is", "a", "test"];newSearchInput = [];for (i = 0, j = searchInput.length; i < j; i++) {    cur = searchInput[i];    if (cur.length > 3) {        newSearchInput.push(cur);    }}

where newSearchInput will only contain valid length items, and you still have the original items in searchInput.

DEMO: http://jsfiddle.net/RYAx2/


Solution 3

In addition to the second solution above, a similar, newer Array.prototype method is available to handle that better: filter. Here's an example:

var searchInput, newSearchInput;searchInput = ["this", "is", "a", "test"];newSearchInput = searchInput.filter(function (value, index, array) {    return (value.length > 3);});

DEMO: http://jsfiddle.net/qky7D/


References:


var myArr = [0,1,2,3,4,5,6];

Problem statement:

myArr.splice(2,1);  \\ [0, 1, 3, 4, 5, 6];

now 3 moves at second position and length is reduced by 1 which creates problem.

Solution: A simple solution would be iterating in reverse direction when splicing.

var i = myArr.length;while (i--) {    // do your stuff}


If you have the lodash library installed, they have a sweet gem you might want to consider.

The function is _.forEachRight (iterates over elements of a collection from right to left)

Here is an example.

var searchInput = ["this", "is", "a", "test"];_.forEachRight(searchInput, function(value, key) {    if (value.length < 4) {        searchInput.splice(key, 1);    }});