Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Other ways of getting the highest array value

Tags:

javascript

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.

like image 240
user8758206 Avatar asked Nov 05 '18 10:11

user8758206


2 Answers

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]));
like image 185
Nina Scholz Avatar answered Oct 10 '22 02:10

Nina Scholz


For your code to work, you need to make 2 changes

  • Just like the simple case, you need to make sure you return the value. Because with return the value returned by function will be undefined and hence, the incorrect calculation
  • == is used for comparison, for assignment, you need to use =

function maxValue(a,c) {
    if (c >= a) { a = c }
    return a;
}
console.log([3,8,-4,3].reduce(maxValue));
like image 31
Nikhil Aggarwal Avatar answered Oct 10 '22 02:10

Nikhil Aggarwal