Equivalent of Lodash’s .maxBy in JavaScript

791 Views Asked by At

What is the JavaScript equivalent of Lodash’s .maxBy? I saw the code _.maxBy(values, ...) in a YouTube tutorial on minimax. I didn’t want to use any external dependencies, but when I googled my question, I couldn’t find anything that answered my question.
I do have a guess though - forEach except it also finds the maximum value

1

There are 1 best solutions below

0
On BEST ANSWER

You can see the implementation here, it's open source:

function maxBy(array, iteratee) {
    let result;
    if (array == null) {
        return result;
    }
    let computed;
    for (const value of array) {
        const current = iteratee(value);

        if (
            current != null &&
            (computed === undefined
                ? current === current && !isSymbol(current)
                : current > computed)
        ) {
            computed = current;
            result = value;
        }
    }
    return result;
}