Min array value based on function

JavaScript, Math, Array · Oct 21, 2020

Returns the minimum value of an array, after mapping each element to a value using the provided function.

const minBy = (arr, fn) =>
  Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));

minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], x => x.n); // 2
minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 2

More like this

  • JavaScript Arrays

    Master array manipulation in JavaScript with this ES6 snippet collection.

    Collection · 203 snippets

  • Max array value based on function

    Returns the maximum value of an array, after mapping each element to a value using the provided function.

    JavaScript, Math · Oct 21, 2020

  • Mapped array average

    Calculates the average of an array, after mapping each element to a value using the provided function.

    JavaScript, Math · Oct 21, 2020

  • Mapped array sum

    Calculates the sum of an array, after mapping each element to a value using the provided function.

    JavaScript, Math · Nov 3, 2020