Other ways of getting the highest array value

  • A+

I'm relatively new to JavaScript and am trying to get my head around the ES6 syntax specifically with if statements. I can create simple ES6 functions like:

function test(a,c) { return a+c; } [3,8,-4,3].reduce(test); 

However, if I want to add an if statement, I cannot get the ES6 syntax to work - for example:

function maxValue(a,c) { if (c >= a) { a == c } } [3,8,-4,3].reduce(maxValue); 

I know I can use the Math method to achieve the result via:

var array = [267, 306, 108]; var largest = Math.max.apply(Math, array); // returns 306 

But I want to know how to use the new ES6 syntax properly. I've tried to add if statements in the filter, reduce, map and forEach to achieve the highest value in the array and am having difficulties.

Any help, advice or links to beginner material would be much appreciated, thanks.


You could use a conditional operator with a check for the greater number.

const max = (a, b) => a > b ? a : b;  console.log([3, 8, -4, 3].reduce(max));

This approach does not work, if the array has only one element. In this case, you could use a very low number as start value and check against the given values.

const max = (a, b) => a > b ? a : b;  console.log([3].reduce(max, -Infinity));

For a way, without iterating, you could use Math.max with spread syntax ..., which take the elements of the array as parameter for the calling function.

console.log(Math.max(...[3, 8, -4, 3]));


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: