Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all empty array inside an array

I have resultant array like this,

[["apple","banana"],[],[],[],["kiwi"],[],[]]

How can I remove all the empty [] array so that my resultant array would look like this:

[["apple","banana"],["kiwi"]];


var array = [["apple","banana"],[],[],[],["kiwi"],[],[]];// sample array
like image 573
Dilip G Avatar asked Jan 05 '17 07:01

Dilip G


2 Answers

Use Array.prototype.filter to filter out the empty arrays - see demo below:

var array = [["apple","banana"],[],[],[],["kiwi"],[],[]];// sample array

var result =  array.filter(e => e.length);
console.log(result);

In ES5, you can omit the arrow function used above:

var array = [["apple","banana"],[],[],[],["kiwi"],[],[]];// sample array

var result =  array.filter(function(e) { 
  return e.length;
});
console.log(result);
like image 87
kukkuz Avatar answered Sep 23 '22 02:09

kukkuz


The ES5 compatible code for @kukuz answer.

var array = [["apple","banana"],[],[],[],["kiwi"],[],[]];// sample array

var result =  array.filter(function(x){return x.length});
console.log(result);
like image 28
Akhil Arjun Avatar answered Sep 21 '22 02:09

Akhil Arjun