Why are 857 more than 1000 and 1001? Javascript

I have the following problem: my function takes an array containing 4 arrays, each element is a number. Functions should 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 ] 

This seems to work, but when I tried with the last array [1000, 1001, 857, 1], in which 1000 and 1001 are greater than 857, I get 857. Why is this happening?

+5
source share
3 answers

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 numbers, use a custom comparison function.

In 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
Sort without comparison function: 1,200,40,5
Sorted using compareNumbers: 1,5,40,200

+10
source

The array#sort method is used, which compares values ​​as strings, not numbers. The best solution uses array.prototype.map and Math.max.apply

 function largestOfFour(array) { return array.map(function(arr) { return Math.max.apply(Math,arr); }); }); largestOfFour([[4,5,1,3],[13,27,18,26],[32,35,37,39],[1000,1001,857,1]]) => [5,27,39,1001] 

You can also pass an array#sort function and do something like this

 array.sort(function(a,b) { return a - b }) 

The pop() function removes and returns the last element of the array. In this case, it will be 1001.

+2
source

Bottom line: 8 greater than 1 .

Here is a short article on this topic: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Try the following:

 arr.sort(function(a, b){return ab}).pop(); 

Or just Math.max()

+2
source

Source: https://habr.com/ru/post/1232229/


All Articles