I have the following problem, my function accepts an array that contains 4 arrays, each element is a number. The functions must return the largest element of each array.
function largestOfFour(arr) {
var largest = [];
for (var i = 0; i < arr.length; i++) {
largest.push(arr[i].sort().pop());
}
console.log(largest);
return largest;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Results:
Array [ 5, 27, 39, 857 ]
Apparently it works, but when I tried with the last array [1000, 1001, 857, 1], in which 1000 and 1001 are larger than 857 I'm getting 857. Why does it happen?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Array values are sorted as strings. If you want to sort as numbers, use a custom comparitor function.
From the MDN docs:
var numberArray = [40, 1, 5, 200];
function compareNumbers(a, b) {
return a - b;
}
console.log('numberArray:', numberArray.join());
console.log('Sorted without a compare function:', numberArray.sort());
console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));
output:
numberArray: 40,1,5,200
Sorted without a compare function: 1,200,40,5
Sorted with compareNumbers: 1,5,40,200
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With