1

How to check if there is at least one element in an array? (I want to verify if the array is not empty.)

Sorry for this silly question, I already spent too much time on Google... (Google only returns complex situations and solutions. It seems like my question is too simple.).

EDIT: Ok, but what will happen with an array like [,,[],,[],,,] ? For my purposes, it should be considered as empty.

EDIT 2: Sorry, guys, for the confusion! At first, I didn't even know exactly what I was looking for. Thank you all!

Emilio
  • 1,314
  • 2
  • 15
  • 39

2 Answers2

1

This would fulfill your new requirements:

function isEmpty(arr) {
    if (!Array.isArray(arr)) {
        return false;
    }

    return arr.every(isEmpty);
}

What it does: with the help of Array.prototype.every it checks that the every item left is an empty array. And the array holes are automatically skipped by .every().

References:

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • This would only work for a second dimension, right? Any clue on how to reach the third, fourth or fifth dimension? – Emilio Sep 21 '16 at 02:54
  • @Emilio it is recursive and would work with any depth. `isEmpty([,,,[[],[],,,,[[[]]]],,,]) // true` – zerkms Sep 21 '16 at 02:54
-1

You could also use truthiness here. This would help you check against undefined at the same time. [] is falsy, so you could do this:

var arr = [];

if(!arr) {
  ... arr is undefined or empty array
} else {
  ... arr has at least one value
}
brandon-barnett
  • 1,035
  • 9
  • 13