Alex Alex - 13 days ago 5
Javascript Question

Js array returns always the highest value

I have the following code:

var max_value = function(array) {
var result = array[0];

for (var i = 0; i < array.length; i++) {
if (array[i] > result) {
result = array[i];
};
}
return result;
}
console.log(max_value([1, 10, 9]));


this returns 10 either like this:

console.log(max_value([1, 10, 9]));


or

console.log(max_value([10, 1, 9]));


if the condition is true should the last array number be returned? (9 in the last case, it seems like the highest number is returned)

Answer

You could use the native Array.protoype.sort to do the hard work for you.

var max_value = function(array) {
  return array.sort((a, b) => a - b).pop()
}
console.log(max_value([1, 10, 9, 5, 3, 2, 6, 8, 4]));

Comments