Reputation: 53
I run an process that generates an array of arrays. But sometimes it will generate an array with empty elements
[
[1,'a','b'],
[2,'b','c'],
[3,'c','d'],
['', '', ''],
['', '', ''],
]
I need remove those arrays. I tried using filter function
array.filter(el => el !== '');
But doesn't work. Also try different ways with for or foreach loop, but nothing.
Upvotes: 2
Views: 155
Reputation: 6390
You can try this:
const arr =
[
[1,'a','b'],
[2,'b','c'],
[3,'c','d'],
['', '', ''],
['', '2', ''],
];
const res = arr.reduce((a, c) => {
const value = c.filter(v => v !== '');
if (value.length > 0) {
a.push(value);
}
return a;
});
console.log(res);
.as-console-wrapper{min-height: 100%!important; top: 0}
Upvotes: 0
Reputation: 21
Does array refer to the multidimensional array itself? If so, then el would refer to each 1D array element within the 2D array. No array is equal to '' so this won't work. Try using map to access each 1D array and call filter on each of those.
array.map(arr => arr.filter(el => el !== ''))
Upvotes: 0
Reputation: 8481
You could use Array.every() to check if all elements of a subarray are empty strings:
const array = [
[1,'a','b'],
[2,'b','c'],
[3,'c','d'],
['', '', ''],
['', '', ''],
];
const filtered = array.filter(a => !a.every(el => el === ''));
console.log(filtered);
Upvotes: 5