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.
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.
Share Improve this question asked Jun 16, 2017 at 10:06 Ayush GuptaAyush Gupta 9,29511 gold badges62 silver badges97 bronze badges 4- Create a recursive function, maybe? – Adam Azad Commented Jun 16, 2017 at 10:08
-
3
arr.toString().replace(/,/g,'') === true
– user7929528 Commented Jun 16, 2017 at 10:09 - ^^^ This will fail if the array is full strings of mas – user7929528 Commented Jun 16, 2017 at 10:16
-
arr.toString().replace(/,/g, '') === '';
– Yosvel Quintero Commented Jun 16, 2017 at 10:48
4 Answers
Reset to default 16An 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.
You can do:
const arr = [[[]],[]]
const isEmpty = a => a.toString().replace(/,/g, '') === ''
console.log(isEmpty(arr))
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./docs/#flattenDeep
Another pact solution that utilises concat
:
[].concat.apply([], [[], [], []]).length; // 0