简体   繁体   中英

How to check if array contains more than one element?

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?

_.compact(array).length > 1

Compact 返回删除了 falsey 值的数组(false、null、0、""、undefined 和 NaN)。

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/

This is the atLeast() function, which works like _.some() , but accepts a min number. If the callback returns true a number of times that is identical to min , the function will return true .

 // the parameters order is to maintain compatability with lodash. A more functional order would be - cb, min, arr function atLeast(arr, min, cb) { cb = cb || _.identity; // default is like some var counter = 0; return _.some(arr, function(v) { cb(v) && counter++; return counter === min; }); } _.mixin({ 'atLeast': atLeast }); var arr1 = [1, 0, null, undefined]; var arr2 = [null, undefined, 0]; var isNotNil = _.negate(_.isNil); // not null or undefined console.log(_.atLeast(arr1, 2, isNotNil)); console.log(_.atLeast(arr2, 2, isNotNil));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM