Given an array of values [1,2,0,-5,8,3], how can I get the maximum value in JavaScript?
I know I can write a loop and keep track of the maximum value, but am looking for a more code-efficient way of doing so with the JavaScript syntax.
Given an array of values [1,2,0,-5,8,3], how can I get the maximum value in JavaScript?
I know I can write a loop and keep track of the maximum value, but am looking for a more code-efficient way of doing so with the JavaScript syntax.
You can use Math.max and ES6 spread syntax (...):
let array = [1, 2, 0, -5, 8, 3];
console.log(Math.max(...array)); //=> 8
Math.max.apply(false, arr)reduce it sometimes wins and sometimes loses. Plus efficiency shouldn't even matter, we're talking less than 1 millisecond.Math.max(...arr) will likely be somewhat slower than Math.max.apply(null, arr) but nowhere near as 'not efficient'. Neat JS features are almost always a trade-off. If you have other information that can be proven with numbers, please, consider providing an answer in dupe question. Even though this has been discussed on SO countless times, new good answers are always good.You can use the following:
yourArray.reduce((max, value) => {return Math.max(max, value)});
The reduce will itterate over values in the array, at each time returning the maximum of all of the values before the current one.
( … ) => … for an implicit return ...0, -1 or -Infinity.