I'm looking for a method for javascript returns true or false when it's empty.. something like Ruby any?
or empty?
[].any? #=> false
[].empty? #=> true
This question is related to
javascript
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
Array has a length property :
[].length // 0
[0].length // 1
[4, 8, 15, 16, 23, 42].length // 6
I'm a little late to the party, but...
[].some(x => !!x)
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
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
.
var a = [];
a.length > 0
I would just check the length. You could potentially wrap it in a helper method if you like.
I believe this to be the cleanest and readable option:
var empty = [];
empty.some(x => x); //returns false
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) }
} );
__
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
Just use Array.length
:
var arr = [];
if (arr.length)
console.log('not empty');
else
console.log('empty');
See MDN
Source: Stackoverflow.com