最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 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.

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
发布评论

评论列表(0)

  1. 暂无评论