Home > front end >  Can you use the Array.prototype.find() to check against more than one condition to find something?
Can you use the Array.prototype.find() to check against more than one condition to find something?

Time:07-12

I am creating a calculator app in JS and I got it to work by using the mouse to click buttons on the screen so I am now integrating the use of the keyboard. Long story short, in part of my functionality before the keyboard was being used I was using the find property on an array to find the last operator clicked that was NOT the = btn and it worked perfectly fine:

lastOperatorThatIsNotEqual = operatorArray.reverse().find(e => e !== "=")

Now that I am using the keyboard, when I click enter I want it to be the equivalent of clicking the = btn so I tried doing it this way using an external function and an if/else statement

function test(e) {
    if (e !== 'Enter') {
        return e
    } else if (e !== '=') {
        return e
    } else {
        console.log('wrong')
    }
}

lastOperatorThatIsNotEqual = operatorArray.reverse().find(test)

However the above does not work. If I remove the else if portion so it's just e !== 'Enter' or e !== '=' then it works fine but I can't have both in there at the same time. I figure it's probably more efficient to have it check that way instead of doing two functions but can't figure out why this isn't working.

Any suggestions are much appreciated. Thanks!

CodePudding user response:

Your conditions are messed up. This

if (e !== 'Enter') {
    return e
} else if (e !== '=') {
    return e
}

will invariably result in one of those branches being fulfilled. If the first condition isn't fulfilled, then e is 'Enter', so e !== '=' is fulfilled.

You should also return a boolean (or a value that's known to be truthy or falsey) from a .filter callback - don't return the value being iterated over, because if the value is falsey, it won't be included in the resulting array.

const lastOperatorThatIsNotEqual = operatorArray.reverse().find(
  e => e !== "=" && e !== 'Enter'
)

or

function test(e) {
    if (e === 'Enter') {
        return false;
    }
    if (e === '=') {
        return false;
    }
    return true;
}

lastOperatorThatIsNotEqual = operatorArray.reverse().find(test)

CodePudding user response:

Return a boolean from find. Try this:

function test(e) {
  return e === 'Enter' || e === '='
}
  • Related