Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to clear undefined values from an array

I'm trying to loop through an array and delete and skip the elements until only one is existing. i've tried splicing but it messes up my loop because the element from arr[1] then becomes arr[0] etc.

Let's say there are 10 people. I'd like to remove person 1 then keep person 2 then remove person 3 and keep person 4. This pattern will go on until only one is left.

any kind of help will do.

like image 307
KT. Avatar asked Mar 07 '12 05:03

KT.


People also ask

How do you remove null values from an array?

To remove all null values from an array:Declare a results variable and set it to an empty array. Use the forEach() method to iterate over the array. Check if each element is not equal to null . If the condition is satisfied, push the element into the results array.

How do you remove an undefined list?

An undefined value automatically gets assigned in JavaScript, where no value has been explicitly assigned. To remove all undefined values from the array, you can use the filter() method.

How do you remove values from an array?

If you want to remove an item from an array, you can use the pop() method to remove the last element or the shift() method to remove the first element.


2 Answers

Filter the falsy items:

var a=[1,2,"b",0,{},"",NaN,3,undefined,null,5];
var b=a.filter(Boolean); // [1,2,"b",{},3,5]
like image 88
alexoviedo999 Avatar answered Nov 14 '22 23:11

alexoviedo999


you should not change the collection during the iterating, not just JavaScript but all language, define a new array and add those ones you want to delete in it, and iterate that one later to delete from first one.

like image 21
Simon Wang Avatar answered Nov 14 '22 23:11

Simon Wang