The problem with your code snippet
- This line is incorrect
highamount.sort(function(amount[0], amount[1]))
because your closing your comparator
function with an extra parenthesis.
highamount.sort(function(amount[0], amount[1]))
^
- You're not declaring params in your
compare
function, you're accessing to an undefined object/array amount
.
function(amount[0], amount[1])
^ ^
- The logic of your compare function has a problem because you're accessing to an undefined object/array
amount
, this is similar to the previous problem.
amount[1] - amount[0]
^ ^
- You're not closing the
sort
function correctly, it's missing the closing parenthesis.
return amount[1] - amount[0];
};
^
- Great, now let's analyze your logic.
Imagine your code has a correct syntax:
var highamount = [50, 100, 2];
highamount.sort(function(a, b) {
return a - b;
});
console.log(highamount);
See? your logic it's Ok because the array highamount
was sorted. Now you can get the max value executing: highamount[highamount.length - 1]
Better approach
Good, how we can improve your approach to find the max value from your array highamount
.
The most recent Javascript version provides good capabilities to accomplish your scenario:
With that operator, you can literally spread your Array and pass its values as params to other functions, arrays, Etc.
So, you can do the following:
var highamount = [50, 100, 2];
var max = Math.max(...highamount);
console.log(max);
See? Amazing how Javascript provides a readable way to accomplish your scenario.
Now, you wrote: And what if I don't have a defined array before and just want to sort it when I call the function, what would be in the function then?
Final approach
Well, you can declare a function which receives an array to find the max value.
Run this code snippet:
var highamount = [50, 100, 2];
var findMax = function(array) {
return array === undefined || array === null || array.length === 0 ? null : Math.max(...array);
}
console.log(findMax(highamount));
console.log(findMax(null));
console.log(findMax(undefined));
console.log(findMax([]));
See? the function findMax
returns the max value according to the passed array.
Resources