some() function is not working with && operator

I´m triying to use the some() function with && operator, but always return false, even if both conditions are inside in the array. For example:

  if (acciones.some(a => a.accionID == 7 && a.accionID == 8)) {
    return true;
  } else {
    return false;
  }

Upvotes: 2

Views: 533

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074295

You're checking one specific accionID on each call to the some callback. That one accionID cannot be both == 7 and == 8 at the same time. Any given accionID will be 7 or 8.

If you want to see if all of the acciones have accionID of 7 or 8, use every with ||:

if (acciones.every(a => a.accionID == 7 || a.accionID == 8)) {
// ----------^--------------------------^

If you want to see if any of the acciones has an accionID of 7 or 8, use some with ||:

if (acciones.some(a => a.accionID == 7 || a.accionID == 8)) {
// ----------^-------------------------^

If acciones has at least one entry in it where accionID is (say) 6, the every check will be false, and the some check will be true.


Since some and every already return a boolean, there's no need for:

if (acciones.every(a => a.accionID == 7 || a.accionID == 8)) {
    return true;
} else {
    return false;
}

Just use

return acciones.every(a => a.accionID == 7 || a.accionID == 8);

In general, if you find yourself writing:

if (x) {
    return true;
} else {
    return false;
}

then:

  1. If x is already a boolean, you can do just

    return x;
    
  2. If x is not necessarily boolean (and it matters that you return a boolean, specifically), you can use the !! idiom to make it a boolean:

    return !!x;
    

Similarly, if you find yourself writing:

if (x) {
    return false;
} else {
    return true;
}

you can always write that as

return !x;

instead.

Upvotes: 4

Related Questions