-1

I have an array with a length of 12. how can I check all the arrays of the array are empty?

let array = [[],[],[],[],[],[],[],[],[],[],[],[]]
7
  • 5
    Would array.every(arr => arr.length < 1) work? Commented Apr 9, 2021 at 9:18
  • Another way could be to flatten and check the length: arr.flat().length == 0 Commented Apr 9, 2021 at 9:21
  • 1
    array.join('') === "" Commented Apr 9, 2021 at 9:23
  • 1
    Duplicate (some transfer needed...!): How to check if all array values are blank in Javascript Commented Apr 9, 2021 at 9:28
  • @georg not if there's an empty string somewhere inside Commented Apr 9, 2021 at 9:33

3 Answers 3

1

On each element, you could do a strict check with Array.isArray (to avoid empty string "" and object {length: 0}) and then check its length

const array = [[],[],[],[],[],[],[],[],[],[],[],[]]
const falseArray1 = [[1],[],[],[],[],[],[],[],[],[],[],[]]
const falseArray2 = ["",[],[],[],[],[],[],[],[],[],[],[]]
const falseArray3 = [{length:0},[],[],[],[],[],[],[],[],[],[],[]]


const isValid = arrayOfArray => arrayOfArray.every(arr => Array.isArray(arr) && arr.length === 0)

console.log(isValid(array))
console.log(isValid(falseArray1))
console.log(isValid(falseArray2))
console.log(isValid(falseArray3))

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

Comments

1

You just need to iterate through every array and checks if all the sub-arrays are empty

array.every(subArr => subArr.length === 0)

5 Comments

Please don't post an answer if the answer is a link to the docs and a single line of code. Stackoverflow is primarily about creating an exhaustive FAQ of common programming problems, not about rehashing the docs to beginners.
I'm explaining that he needs to iterate through his array and using the every function ( which I gently give the doc link for him to check if he doesn't know ... ) I'm not "rehashing" anything ... Sorry to try to help ... At least I'm not here just to criticize...
Neither am I. I'm just explaining my downvote. Helping people is fine obviously, but you can do that in a comment.
Good point that at least you did ... Because I didn't get it for sur .... Look at the first comment that already has 4 upvote ... But still is more concise that my answer is....
Don't take it personal; people with 10k rep are posting answers to this even though it's a very probable duplicate and indeed turned out to be one.
0

I think the easiest approach would be to create a function, i,e:

function checkEmpty(array) {
  return Array.isArray(array) && (array.length == 0 || array.every(isEmpty));
}

You can then test which arrays you'd like. For example:

console.log(checkEmpty([[], [[]]]));

Output:

true

You can then use this boolean value to your advantage and work with anything else you'd like.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.