Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 857 larger than 1000 and 1001? Javascript [duplicate]

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?

like image 582
L. San Avatar asked Sep 24 '15 22:09

L. San


1 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 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

like image 116
meagar Avatar answered Oct 18 '22 02:10

meagar