Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete zero values from Array with JavaScript

I have an array with name "ids" and some values like ['0','567','956','0','34']. Now I need to remove "0" values from this array. ids.remove ("0"); is not working.

like image 827
vissu Avatar asked Apr 28 '11 11:04

vissu


1 Answers

Here's a function that will remove elements of an array with a particular value that won't fail when two consecutive elements have the same value:

function removeElementsWithValue(arr, val) {
    var i = arr.length;
    while (i--) {
        if (arr[i] === val) {
            arr.splice(i, 1);
        }
    }
    return arr;
}

var a = [1, 0, 0, 1];
removeElementsWithValue(a, 0);
console.log(a); // [1, 1]

In most browsers (except IE <= 8), you can use the filter() method of Array objects, although be aware that this does return you a new array:

a = a.filter(function(val) {
    return val !== 0;
});
like image 158
Tim Down Avatar answered Oct 30 '22 09:10

Tim Down