How can i remove an some types of elements is js?

Viewed 62

I want to remove all of 0, false, undefined and "" elements in my list.

Here is my code:

var  a = [ 1232, "fesr", undefined,undefined, true, 0, false ,'',false , false , undefined]
console.log(a);

for(var i=0 ; i < a.length ; i++){
    if(a[i]===0 || a[i]===false || a[i]==='' || a[i]===undefined  ){
        a.splice(i,2)
    }else{
        continue
    }
}
console.log(a); 

input :

[ 1232, "fesr", undefined,undefined, true, 0, false ,'',false , false , undefined]

output:

[ 1232, "fesr", true, "", undefined ]

As you see first my code does not remove "" .

second problem is it does not remove all of 0, false and undefined elements if we have a greater number of them!

How can i solve that?

3 Answers

The easy way:

const data = [1232, "fesr", undefined, undefined, true, 0, false, '', false, false, undefined];
const result = data.filter(Boolean);
console.log(result)

In your code you use splice method that mutates your source array, that's why you receive incorrect result.

what you did was iterating over the array and then, splice by index. But if you begin in the Front, he removes first index 3 in your example, goes to the next, i is 4 now, but the next value is in 3 again. You have to do it reverse, to do it with splice by index

var  a = [ 1232, "fesr", undefined,undefined, true, 0, false ,'',false , false , undefined];
console.log(a);

for(var i = a.length - 1; i >= 0; i--){
    if (a[i] === 0 || a[i] === false || a[i] === '' || a[i] === undefined){
        a.splice(i, 1);
    } else {
        continue;
    }
}
console.log(a); 

const input = [ 1232, "fesr", undefined,undefined, true, 0, false ,'',false , false , undefined]

const output = []
input.forEach(item => {
  if (item) output.push(item)
})
console.log(output)

Related