Introduction
In this lab, we will dive into a JavaScript programming challenge where we will be tasked with creating a function that returns the maximum value of an array, after mapping each element to a value using the provided function. By using Array.prototype.map() and Math.max(), we will be able to efficiently achieve this task and gain a better understanding of these essential JavaScript methods.
How to Find the Maximum Value of an Array Based on a Function
To find the maximum value of an array based on a function, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.map()to map each element of the array to the value returned by the provided function,fn. - Use
Math.max()to get the maximum value of the mapped array.
Here's an example code snippet that implements the above steps:
const maxBy = (arr, fn) =>
Math.max(...arr.map(typeof fn === "function" ? fn : (val) => val[fn]));
To use the maxBy function, pass in an array and the function that should be used to map each element to a value. You can either pass in a function directly or a string representing the key that should be used to access the value in each object of the array.
Here are some example calls to the maxBy function:
maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], (x) => x.n); // returns 8
maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], "n"); // returns 8
Summary
Congratulations! You have completed the Max Array Value Based on Function lab. You can practice more labs in LabEx to improve your skills.