Reputation: 6130
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
Upvotes: 226
Views: 280155
Reputation: 91
// 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)}`);
});
Upvotes: 1
Reputation: 1277
Just use ternary operator
let myArray = []
myArray && myArray.length ? console.log(true) : console.log(false)
Upvotes: -1
Reputation: 5667
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);
Upvotes: 1
Reputation: 1627
I believe this to be the cleanest and readable option:
var empty = [];
empty.some(x => x); //returns false
Upvotes: 18
Reputation: 215029
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.
Upvotes: 134
Reputation: 15216
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
Upvotes: 263
Reputation: 93481
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
Upvotes: 4
Reputation: 93481
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
Upvotes: 3
Reputation: 63579
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
Upvotes: 4
Reputation: 413966
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
.
Upvotes: 13
Reputation: 49135
Just use Array.length
:
var arr = [];
if (arr.length)
console.log('not empty');
else
console.log('empty');
See MDN
Upvotes: 5
Reputation: 39278
var a = [];
a.length > 0
I would just check the length. You could potentially wrap it in a helper method if you like.
Upvotes: 18
Reputation: 2075
Array has a length property :
[].length // 0
[0].length // 1
[4, 8, 15, 16, 23, 42].length // 6
Upvotes: 3