Reputation: 529
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
Upvotes: 11
Views: 15871
Reputation: 11
the bottom_line; pass any value that is considered falsey in the filter function and it'll be filtered out
const array = [["apple","banana"],[],[],[],["kiwi"],[],[]];
var result = array.filter(e => e[0]);
console.log(result);
Upvotes: 1
Reputation: 339
Use the following code:
var newArray = array.filter(value => JSON.stringify(value) !== '[]');
Upvotes: 3
Reputation: 1137
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);
Upvotes: 5
Reputation: 42352
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);
Upvotes: 17
Reputation: 74738
Use Array.prototype.filter() to get a new filtered array:
var array = [["apple","banana"],[],[],[],["kiwi"],[],[]];
var newArr = array.filter(function(obj){
return obj[0] !== undefined;
});
console.log(JSON.stringify(newArr, 0, 0));
Upvotes: 3