Vissu
Vissu

Reputation: 2043

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.

Upvotes: 16

Views: 38718

Answers (9)

jesal
jesal

Reputation: 7938

Here's one way to do it:

const array = ['0', '567', '956', '0', '34'];
const filtered = array.filter(Number);

console.log(filtered);

Upvotes: 14

Khalid Saifullah Fuad
Khalid Saifullah Fuad

Reputation: 144

The easy approach is using splice!!. But there's a problem, every time you remove an element your array size will constantly reduce. So the loop will skip 1 index the array size reduces.

This program will only remove every first zero.

// Wrong approach
let num = [1, 0, 0,  2, 0, 0, 3,];

for(let i=0; i<num.length; i++){
    if(num[i]==0)
        num.splice(i, 1);
}
console.log(num)

the output will be

[1,0,2,0,3]

So to remove all the zeros you should increase the index if you found the non-zero number.

let i = 0;
while(i<num.length){
    if(num[i]==0){
        num.splice(i,1);
    }
    else{
        i++;
    }
}

But there's a better way. Since changing the size of the array only affects the right side of the array. You can just traverse in reverse and splice.

for(let i=num.length-1; i>=0; i--){
    if(num[i]===0)
        num.splice(i,1);
}

Upvotes: 0

Nithin Sai
Nithin Sai

Reputation: 1013

I believe, the shortest method is

var newList = ['0', '567', '956', '0', '34'].filter(cV => cV != "0")

You could always do,

listWithZeros = ['0', '567', '956', '0', '34']
newList = listWithZeros.filter(cv => cv != "0")

The newList contains your required list.

Explanation

Array.prototype.filter()

This method returns a new array created by filtering out items after testing a conditional function

It takes in one function with possibly 3 parameters.

Syntax:

Array.prototype.filter((currentValue, index, array) => { ... })

The parameters explain themselves.

Read more here.

Upvotes: 2

Adrian Swifter
Adrian Swifter

Reputation: 99

For ES6 best practice standards:

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


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

(note that your "id's" are strings inside array, so to check regardless of type you should write "!=")

Upvotes: 5

avoliva
avoliva

Reputation: 3356

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

Upvotes: 2

Adria
Adria

Reputation: 9031

For non-trivial size arrays, it's still vastly quicker to build a new array than splice or filter.

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 );
  }
}

If you do splice, iterate backwards!

Upvotes: 4

Tim Down
Tim Down

Reputation: 324477

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;
});

Upvotes: 18

Harry Joy
Harry Joy

Reputation: 59650

Use splice method in javascript. Try this function:

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

Parameters are:

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

Upvotes: 15

Ammu
Ammu

Reputation: 5127

Below code can solve your problem

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

Upvotes: 2

Related Questions