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.

3
  • 1
    The values are coerced to a string if they aren't already before comparison. Commented May 20, 2017 at 17:08
  • 1
    The default comparison function is function (a,b) { return String(a).localeCompare(b); } Commented May 20, 2017 at 17:11
  • @4castle, Thanks for the explanation..:) Commented May 20, 2017 at 17:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.