I would like to ensure that an array contains more then one element and that it is not null nor undefined. With other words: I am looking for an alternative to
if(array && array.length > 1)
that would be better to read.
Lodash provides a method for checking if an array contains at least one element:
if(_.some(array))
Is there a similar method for checking for several elements?
Unfortunately following methods do not exist:
if(_.several(array))
if(_.many(array))
Would I have to write my own extension method or did I just not find the right lodash command, yet?
You can create own lodash mixin for that:
var myArray = [1, 2, 3];
var anotherArray = [4];
function several(array) {
return _.get(array, 'length') > 1
}
_.mixin({ 'several': several });
console.log(_.several(myArray)) // ==> true
console.log(_.several(anotherArray)) // ==> false
Example: https://jsfiddle.net/ecq7ddey/