Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an Array is an Array of empty Arrays in Javascript

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.

like image 992
Ayush Gupta Avatar asked Nov 21 '25 09:11

Ayush Gupta


2 Answers

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.

like image 58
georg Avatar answered Nov 23 '25 23:11

georg


You can do:

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

console.log(isEmpty(arr))
like image 33
Yosvel Quintero Arguelles Avatar answered Nov 23 '25 21:11

Yosvel Quintero Arguelles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!