0

UPDATE - Thanks @baoo for referring me to a similar question. I guess I should search more extensively on SO for similar questions, before making one of my own.

I am trying to sort an array using the 'sort' function in JS as follows :-

var arr = [4, 3, 2, 1, 10];
console.log(arr.sort());

However, instead of the expected output as [1, 2, 3, 4, 10], the actual output obtained is [1, 10, 2, 3, 4].

Upon searching on the Web, I found that the values are getting sorted as string.

However, the type of the elements is indeed a 'number', as could be verified with the following code :-

typeof(arr[0]) // outputs 'number'

Further, with the following code the expected output of [1, 2, 3, 4, 10] is indeed obtained :-

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

Could someone please throw some light on what exactly is happening here ?

Thanks.

Naman Sancheti
  • 414
  • 1
  • 8
  • 18

0 Answers0