Remove empty elements from an array in Javascript

York Chen
1 min readAug 26, 2020

--

var array = [9, 8, null, 2, “”, undefined, 3,,,,,, 4,, 4,, 5,, 6,,1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,];

1.use filter()

var filtered = array.filter(function (elements) {
return elements != null;
});
console.log(filtered);

2.use push() and splice()

//clear null ,"", undefined ,0

len = array.length;

// copy
for(i = 0; i < len; i++ ){
array[i] && array.push(array[i]);
}


// cut
array.splice(0 , len);

console.log("use push() and splice()",array);

3.using ES6 and push()

//clear null ,"", undefined ,0
temp = [];

// copy to new array
for(let i of array )
i && temp.push(i);

array= temp;

console.log("use ES6",array);

--

--

York Chen
York Chen

Written by York Chen

Cooking is an indispensable part of life. It is a taste that can’t be forgotten.

No responses yet