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
5 Answers 5
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);
answered Jan 5, 2017 at 7:22
kukkuz
42.5k6 gold badges65 silver badges103 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Kraang Prime
Nice solution. I really wish more people coded using this syntax -- would make all that JavaScript debugging go so much easier (and faster page load times)
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);
answered Jan 5, 2017 at 7:27
Akhil Arjun
1,1277 silver badges12 bronze badges
1 Comment
Akhil Arjun
sorry! didn't notice @Jai
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));
answered Jan 5, 2017 at 7:24
Jai
74.8k12 gold badges77 silver badges104 bronze badges
Comments
Use the following code:
var newArray = array.filter(value => JSON.stringify(value) !== '[]');
1 Comment
Dietrich
Thank you, works well for empty objects with
var newArray = array.filter(value => JSON.stringify(value) !== '{}');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);
k.tten
26.8k4 gold badges34 silver badges63 bronze badges
Comments
lang-js
splice()function provided in the Array prototype.var array = [["apple","banana"],[],[],[],["kiwi"],[],[]].filter((x) => { return x.length})