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
PS I know I can do it using an level for loop, but was wondering about a more optimized solution.
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.
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
You can do:
var arr = [[[]],[]], isEmpty = a => a.toString().replace(/,/g, '') === ''; console.log(isEmpty(arr));
另一个利用concat
紧凑型解决方案:
[].concat.apply([], [[], [], []]).length; // 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.