11

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
6
  • use Array.prototype.filter(). Commented Jan 5, 2017 at 7:20
  • you can iterate through the parent array and use the splice() function provided in the Array prototype. Commented Jan 5, 2017 at 7:20
  • Possible duplicate of How can I remove empty object in from an array in JS Commented Jan 5, 2017 at 7:21
  • 2
    var array = [["apple","banana"],[],[],[],["kiwi"],[],[]].filter((x) => { return x.length}) Commented Jan 5, 2017 at 7:21
  • 2
    @DilipG - answers do not need to be accepted to be duplicates. Often there are unaccepted solutions that work. In this case, there is a solution that will do what you ask on that page Commented Jan 5, 2017 at 7:24

5 Answers 5

17

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);

Sign up to request clarification or add additional context in comments.

1 Comment

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)
5

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);

1 Comment

sorry! didn't notice @Jai
3

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));

Comments

3

Use the following code:

var newArray = array.filter(value => JSON.stringify(value) !== '[]');

1 Comment

Thank you, works well for empty objects with var newArray = array.filter(value => JSON.stringify(value) !== '{}');
1

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.