233

I'm looking for a method for JavaScript that returns true or false when it's empty... something like Ruby any? or empty?

[].any? #=> false
[].empty? #=> true
0

14 Answers 14

275

The JavaScript native .some() method does exactly what you're looking for:

function isBiggerThan10(element, index, array) {
  return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
Sign up to request clarification or add additional context in comments.

16 Comments

Thank you, I see now [12,5,8,1,4].some(function(e){ return e > 10;}); working!
@kangkyu I think it's time to accept this answer ;)
Sorry for late response, but @asiniy I still think the accepted answer should have been accepted because it has more details (including some()) and can be more helpful to others.
@kangkyu Except the currently accepted answer spends more time trying to be Ruby-ish than actually giving a javascript answer. It also recommends writing your own wrapper (which really isn't necessary) and does so in a potentially harmful way (i.e. extending the prototype for something that isn't a polyfill)
@LokiKriasus Extending the prototype may cause future problems (i.e. if in the future javascript defines a any() method, and someone uses it, that code may fail in weird ways when used together with a library that uses this code because you defined it slightly differently) and creates code that is harder to read for other (javascript) developers. And the whole reason for that approach is that a Ruby developer refused to learn that they should write some() instead of any() and that they shouldn't forget to pass a function to it even if the array is empty...
|
138

JavaScript has the Array.prototype.some() method:

[1, 2, 3].some((num) => num % 2 === 0);  

returns true because there's (at least) one even number in the array.

In general, the Array class in JavaScript's standard library is quite poor compared to Ruby's Enumerable. There's no isEmpty method and .some() requires that you pass in a function or you'll get an undefined is not a function error. You can define your own .isEmpty() as well as a .any() that is closer to Ruby's like this:

Array.prototype.isEmpty = function() {
    return this.length === 0;
}

Array.prototype.any = function(func) {
   return this.some(func || function(x) { return x });
}

Libraries like underscore.js and lodash provide helper methods like these, if you're used to Ruby's collection methods, it might make sense to include them in your project.

Comments

48

I'm a little late to the party, but...

[].some(Boolean)

6 Comments

I guess this doesn't play well with [false, 0, '', null, undefined]
It works wonderfully, @BrookJordan. It returns false. The zero in there is questionable, but for the rest, I believe that is the functionality OP was after. Looking for "truthy" entities.
another, arguably more beautiful way of writing this: [].some(x => Boolean)
@phil294 it should be [].some(Boolean)
[].some(x => Boolean) will always return true, so that won't work. @Gershy is correct, [].some(Boolean) actually does what OP asks. some takes a function to run on every element; Boolean is already a function that converts truthy and falsey values to true and false respectively. So by passing Boolean, some checks every element for truthy/falsey, and handles null, undefined, and empty-string.
|
20

I believe this to be the cleanest and readable option:

var empty = [];
empty.some(x => x); //returns false

4 Comments

What if empty contains falsy values?
empty.some(x => true) would work on [undefined, null, false, 0]
@TomHale [false, 0, "", undefined, null, NaN].some(x => x) returns false
If you want to consider those values as valid, use as Holden said: empty.some(x => true)
18
var a = [];
a.length > 0

I would just check the length. You could potentially wrap it in a helper method if you like.

3 Comments

i think the problem is here if you have a big array you are counting all elements unnecessarily
@Snr all major interpreters provide efficient accessors for the length of arrays: stackoverflow.com/questions/9592241/…
This is literally the simplest and best answer beyond all those suggesting to use some. KISS principle!
14

JavaScript arrays can be "empty", in a sense, even if the length of the array is non-zero. For example:

var empty = new Array(10);
var howMany = empty.reduce(function(count, e) { return count + 1; }, 0);

The variable "howMany" will be set to 0, even though the array was initialized to have a length of 10.

Thus because many of the Array iteration functions only pay attention to elements of the array that have actually been assigned values, you can use something like this call to .some() to see if an array has anything actually in it:

var hasSome = empty.some(function(e) { return true; });

The callback passed to .some() will return true whenever it's called, so if the iteration mechanism finds an element of the array that's worthy of inspection, the result will be true.

Comments

5

Just use Array.length:

var arr = [];

if (arr.length)
   console.log('not empty');
else
   console.log('empty');

See MDN

Comments

4

If you really want to got nuts, add a new method to the prototype:

if (!('empty' in Array.prototype)) {
  Array.prototype.empty = function () {
    return this.length === 0;
  };
}

[1, 2].empty() // false
[].empty() // true

DEMO

4 Comments

Thank you for help. I found here for Array.compact (I live in Ruby area) and they say !!(anything truthy) returns true, so it could be something like !!array.filter(function(e){ return e }).length ?
if (!('any?' in Array.prototype)) { Array.prototype.any? = function () {return !!this.filter(function(e){ return e }).length;};} .... I tried this didn't work urgh
Why don't you use georg's? Also, I don't think you can have question marks in method names.
if (!('any' in Array.prototype)) { Array.prototype.any = function () {return !!this.filter(function(e){ return e }).length;};} this works as Array.any() Thank you Andy
4

What you want is .empty not .empty() to fully mimics Ruby :

     Object.defineProperty( Array.prototype, 'empty', {
           get: function ( ) { return this.length===0 }
      } );    

then

[].empty //true
[3,2,8].empty //false

For any , see my answer here

Comments

3

Array has a length property :

[].length // 0
[0].length // 1
[4, 8, 15, 16, 23, 42].length // 6

Comments

3

polyfill* :

Array.prototype.any=function(){
    return (this.some)?this.some(...arguments):this.filter(...arguments).reduce((a,b)=> a || b)
};

If you want to call it as Ruby , that it means .any not .any(), use :

Object.defineProperty( Array.prototype, 'any', {
  get: function ( ) { return (this.some)?this.some(function(e){return e}):this.filter(function(e){return e}).reduce((a,b)=> a || b) }
} ); 

__

`* : https://en.wikipedia.org/wiki/Polyfill

Comments

1

As someone suggested in one of the comments, checking if an array contains any elements can be done with a simple use of some.

let hasItems = array.some(x => true);
let isEmpty = !array.some(x => true);

Comments

1
// test data
const data = [[1,2,3,4,5,6],[], [1,7,10]];

// function to check if any condition is satisfied
const any = (condition) => (data) => data.some(condition);

// function to check if empty
const empty = (data) => !data?.length

data.forEach((f) => {
    console.log(`any ${JSON.stringify(f)} -> ${any(x => x %7 == 0)(f)}`);
    console.log(`empty ${JSON.stringify(f)} -> ${empty(f)}`);
});

1 Comment

Please take a look at the formatting options available for code on Stack Overflow
-1

Just use ternary operator

let myArray = []
myArray && myArray.length ? console.log(true) : console.log(false)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.