2

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.

2
  • 1
    arr.filter(subarr => subarr.some(Boolean)) Commented May 5, 2020 at 20:12
  • In your example el is an array, so you cannot compare it with empty string, instead (if all of elements are empty), you may check whether first item of el is empty (i.e. do el[0]!=='') Commented May 5, 2020 at 20:16

3 Answers 3

5

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

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

3 Comments

A negated .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));.
@CRice you are right about .every and .some but a.some(Boolean) will also filter out any arrays that contain only falsey elements like [0, false, null]
A good point, it is just so. Using the Boolean function makes the snippet shorter, but it is not exactly equivalent to before, as you describe. Caveat Emptor.
0

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

0

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.