2

In my node.js 6.10 app, I am trying to identify in my array looks like this:

[
    [
        []
    ],
    []
]

This nesting can go onto n level, and can have elements in arrays at any level. How can I do this? Thanks

P.S. I know I can do it using a n level for loop, but was wondering about a more optimized solution.

4
  • Create a recursive function, maybe? Commented Jun 16, 2017 at 10:08
  • 3
    arr.toString().replace(/,/g,'') === true Commented Jun 16, 2017 at 10:09
  • ^^^ This will fail if the array is full strings of commas Commented Jun 16, 2017 at 10:16
  • arr.toString().replace(/,/g, '') === ''; Commented Jun 16, 2017 at 10:48

4 Answers 4

16

An one-liner:

let isEmpty = a => Array.isArray(a) && a.every(isEmpty);

//

let zz = [
    [
        []
    ],
    [],
    [[[[[[]]]]]]
]


console.log(isEmpty(zz))

If you're wondering how this works, remember that any statement about an empty set is true ("vacuous truth"), therefore a.every(isEmpty) is true for both empty arrays and arrays that contain only empty arrays.

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

2 Comments

Even simpler to use lodash :)
I think trying to do something any better than this is just waste of time :)
1

You can do:

const arr = [[[]],[]]
const isEmpty = a => a.toString().replace(/,/g, '') === ''

console.log(isEmpty(arr))

Comments

0

Yes,

All you need is to write recursive function, that checks array.length property on its way.

Something like that:

function isEmpty(arr) {
let result = true;

for (let el of arr) {
    if (Array.isArray(el)) {
        result = isEmpty(el); 
    } else {
        return false;
    }
}

return result;

}

You may consider to use lodash: https://lodash.com/docs/#flattenDeep

Comments

-1

Another compact solution that utilises concat:

[].concat.apply([], [[], [], []]).length; // 0

1 Comment

It won't work in case of nested arrays, like: [[], [], [[]]]

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.