Remove null values ​​from array using javascript

I have an array called ids and some values ​​like ['0', '567', '956', '0', '34']. Now I need to remove the "0" values ​​from this array. ids.remove ("0"); does not work.

+8
source share
7 answers

Use splicing method in javascript. Try this feature:

function removeElement(arrayName,arrayElement)
 {
    for(var i=0; i<arrayName.length;i++ )
     { 
        if(arrayName[i]==arrayElement)
            arrayName.splice(i,1); 
      } 
  }

Parameters:

arrayName:-      Name of the array.
arrayElement:-   Element you want to remove from array
+14
source

Here is one way to do this:

['0','567','956','0','34'].filter(Number)
+12
source

, , , :

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]

( IE <= 8) filter() Array, , :

a = a.filter(function(val) {
    return val !== 0;
});
+9

, .

var new_arr = [],
tmp;

for(var i=0, l=old_arr.length; i<l; i++)
{
  tmp = old_arr[i];

  if( tmp !== '0' )
  {
    new_arr.push( tmp );
  }
}

, !

+4

 for(var i=0; i<ids.length;i++ )
 { 
    if(ids[i]=='0')
        ids.splice(i,1); 
  } 
+2

ES6:

let a = ['0','567','956','0','34'];


a = a.filter(val => val !== "0");

( , "" - , "! =")

+2
ids.filter(function(x) {return Number(x);});
+1

All Articles