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.
3 Answers 3
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);
3 Comments
.every is equivalent to a .some with a negated condition. This could be written using the equivalent: const filtered = array.filter(a => a.some(el => el !== ''));, or since empty strings are falsy anyway: const filtered = array.filter(a => a.some(Boolean));..every and .some but a.some(Boolean) will also filter out any arrays that contain only falsey elements like [0, false, null]Boolean function makes the snippet shorter, but it is not exactly equivalent to before, as you describe. Caveat Emptor.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 !== ''))
Comments
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}
arr.filter(subarr => subarr.some(Boolean))elis an array, so you cannot compare it with empty string, instead (if all of elements are empty), you may check whether first item ofelis empty (i.e. doel[0]!=='')