0

I have a question regarding javascript's sort() function

var arr = [23,43,54,2,3,12];
arr.sort();

it's output is [12, 2, 23, 3, 43, 54] well it should be [2, 3, 12, 23, 43, 54]?

3

3 Answers 3

4

It's because you're sorting the numbers with the default sorting algorithm, which converts them to a string and sorts lexicographically.

Instead pass a function defining a sort order via its return value.

var arr = [23,43,54,2,3,12]; 

console.log(arr.sort((a, b) => a - b));

Returning a positive number moves a toward the end of the list.

Sign up to request clarification or add additional context in comments.

Comments

2

You have to specify a sort function

[12, 2, 23, 3, 43, 54].sort(function (a, b) { return  a - b ; } )

The javascript specification states that sort should perform lexicografic sorting, docs

2 Comments

You shouldn't return a boolean. The sorter expects a numeric return value. Returning a boolean may give incorrect results in some cases.
@spanky you are right, changed to address this feedback,
1

The sorting of number is based on Unicode. Hence the oder you have is correct. Refer the link for details.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.