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
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
[12,5,8,1,4].some(function(e){ return e > 10;});
working!
some()
) and can be more helpful to others.
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...
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.
I'm a little late to the party, but...
[].some(Boolean)
[false, 0, '', null, undefined]
Commented
Sep 25, 2019 at 10:31
[].some(x => 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
.
Commented
Jun 11, 2021 at 17:39
I believe this to be the cleanest and readable option:
var empty = [];
empty.some(x => x); //returns false
empty.some(x => true)
would work on [undefined, null, false, 0]
Commented
Jul 23, 2021 at 17:31
[false, 0, "", undefined, null, NaN].some(x => x)
returns false
Commented
Nov 20, 2021 at 14:04
empty.some(x => true)
Commented
Nov 20, 2021 at 14:33
var a = [];
a.length > 0
I would just check the length. You could potentially wrap it in a helper method if you like.
some
. KISS principle!
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
.
Just use Array.length
:
var arr = [];
if (arr.length)
console.log('not empty');
else
console.log('empty');
See MDN
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
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
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
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) }
} );
__
Array has a length property :
[].length // 0
[0].length // 1
[4, 8, 15, 16, 23, 42].length // 6
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);
// 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)}`);
});
Just use ternary operator
let myArray = []
myArray && myArray.length ? console.log(true) : console.log(false)