Why wouldn't lodash 'some' function work as expected?

3.5k views Asked by At

I'm trying to use lodash 2.4.1 in order to know if there's at least one element within an array with true as its value.

So I decided to use lodash some or any function.

This is what my code looks like:

if ( _.some([lineup.reachesMaxForeignPlayers(), lineup.reachesBudgetLimit()], true) ) {
  response.send(400, "La inclusiĆ³n de este jugador no satisface las reglas del juego");
}

Which is never going inside the if block, even that first condition actually evaluates to true.

I got:

console.log(lineup.reachesMaxForeignPlayers());
console.log(lineup.reachesBudgetLimit());

Before the if block and I can actually see first statement evaluating to true.

What could it be failing?

I use lodash 2.4.1 as it's included Sails js dependency.

5

There are 5 answers

1
dting On BEST ANSWER

edit:

Actually, just using _.some[docs] with no predicate defaults to identity:

_.some(bool_arr) 

should work.

console.log(_.some([true, true, false]));
console.log(_.some([false, false, false]));
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.3/lodash.min.js"></script>
 


In addition to the other answers that suggest passing Boolean as the predicate. You can also use:

_.some(bool_arr, _.identity)

_.identity[docs]

This method returns the first argument provided to it.

0
Giuseppe Pes On

You should use a function:

function isTrue(v) {
  return v === true;
}

if ( _.some([lineup.reachesMaxForeignPlayers(), lineup.reachesBudgetLimit()], isTrue) ) {
  response.send(400, "La inclusiĆ³n de este jugador no satisface las reglas del juego"); 
}

Lodash doc: https://lodash.com/docs#some

4
antishok On

I believe you meant to pass Boolean as the predicate (2nd argument)

2
Cymen On

_.some is checking that the collection you give it contains at least one instance of an object of the type you are giving it. Observe:

> _.some([true, false], true)
false

> _.some([true, undefined], Boolean)
true

You can instead pass a function like so:

> _.some([true, false], function(value) { return value === true; })
true

> _.some([undefined, false], function(value) { return value === true; })
false

However, I would suggest using if (lineup.reachesBudgetLimit() || lineup.reachesMaxForeignPlayers()).

0
georg On

When you pass a non-function value to some, lodash treats it as a property name and tries to find an object which contain a non-falsy property with the name given. In your example, you pass true, so it tries to access item1[true], item2[true] etc. Since none of them exists, the result is false.

The solution is to omit the second argument altogether, in which case it defaults to identity, that is, to the element itself.