Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty elements from an array in Javascript

How do I remove empty elements from an array in JavaScript?

Is there a straightforward way, or do I need to loop through it and remove them manually?

like image 244
Tamas Czinege Avatar asked Nov 11 '08 15:11

Tamas Czinege


People also ask

How do you delete empty elements in an array?

In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function.

How do you remove an element from an array with value?

To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.


1 Answers

Simple ways:

var arr = [1,2,,3,,-3,null,,0,,undefined,4,,4,,5,,6,,,,];   arr.filter(n => n) // [1, 2, 3, -3, 4, 4, 5, 6]  arr.filter(Number)  // [1, 2, 3, -3, 4, 4, 5, 6]  arr.filter(Boolean)  // [1, 2, 3, -3, 4, 4, 5, 6] 

or - (only for single array items of type "text")

['','1','2',3,,'4',,undefined,,,'5'].join('').split('');  // output:  ["1","2","3","4","5"] 

or - Classic way: simple iteration

var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],     len = arr.length, i;  for(i = 0; i < len; i++ )     arr[i] && arr.push(arr[i]);  // copy non-empty values to the end of the array  arr.splice(0 , len);  // cut the array and leave only the non-empty values  arr // [1,2,3,3,[],Object{},5,6] 


via jQuery:

var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];  arr = $.grep(arr,function(n){ return n == 0 || n });  arr // [1, 2, 3, 3, 0, 4, 4, 5, 6] 


UPDATE - just another fast, cool way (using ES6):

var arr = [1,2,null, undefined,3,,3,,,0,,,4,,4,,5,,6,,,,],      temp = [];  for(let i of arr)     i && temp.push(i); // copy each non-empty value to the 'temp' array  arr = temp;  arr // [1, 2, 3, 3, 4, 4, 5, 6] 

Remove empty values

['foo', '',,,'',,null, ' ', 3, true, [], [1], {}, undefined, ()=>{}].filter(String)  // ["foo", null, " ", 3, true, [1], Object {}, undefined, ()=>{}] 
like image 110
31 revs, 7 users 77% Avatar answered Sep 28 '22 12:09

31 revs, 7 users 77%