5

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.

3
  • 1
    Second result from 'max of array in javascript' on google ^ Commented Jul 15, 2017 at 23:04
  • Agree, maybe edit the other to include the word armax though... Coming from python, that's what I instictively googled and nothing came up... Commented Jul 15, 2017 at 23:16
  • I would say it has a reasonable title. Regardless of language, I would have search 'max of array in <language>', but that's just me. Commented Jul 15, 2017 at 23:17

2 Answers 2

13

You can use Math.max and ES6 spread syntax (...):

let array = [1, 2, 0, -5, 8, 3];

console.log(Math.max(...array)); //=> 8

Sign up to request clarification or add additional context in comments.

11 Comments

Or without the spread operator Math.max.apply(false, arr)
The spread operator is not efficient.
@ibrahimmahrir There is no spread 'operator', it's syntax.
@ibrahimmahrir Is it? I tested and against reduce it sometimes wins and sometimes loses. Plus efficiency shouldn't even matter, we're talking less than 1 millisecond.
@ibrahimmahrir 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.
|
1

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.

3 Comments

Or just ( … ) => … for an implicit return ...
Also, why through the trouble of a reduce operation when spread syntax exists??
You might want to provide some reasonable default value that is returned when the array is empty, such a 0, -1 or -Infinity.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.