How JS sorting the numbers?
Asked Answered
C

3

7

I'm learning Javascript and I faced a problem with sorting numbers I don't understand how work sorting function and I find an other way to sort the numbers but it was with list not with arrays I need explanations. I also see this link : Sorting array with numbers without sort() method

const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;

points.sort(function(a, b) {
  return a - b
});
document.getElementById("demo2").innerHTML = points;

document.getElementById("demo3").innerHTML = points.sort();
unsorted:
<div id="demo1"></div>
sorted:
<div id="demo2"></div>
sorted alphabetically:
<div id="demo3"></div>
Checker answered 18/6, 2022 at 17:6 Comment(5)
It’s not clear what you’re asking, or in JS what you mean by list versus array. If you’re asking how to write a sort function there are many references available.Exactly
Your code works as is. I added the missing HTML to the snippet and now you can see for yourself.Punchinello
Checkout the MDN resources on Array.prototye.sort() and you will understand the role of the callback function: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . If you want to learn how sort algorithms work in general then maybe you should google "bubble sort" or "quicksort".Punchinello
I'm guessing you're saying you don't understand why you need a sorting a function. This is because by default, JavaScript converts the elements of an array to strings and sorts them based on UTF-16 values. Even your array of only numbers will be converted to, and compared as, strings. You should read the documentation for sort: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Dotted
The sort function sorts by dictionary order by default unless you override it with a function. So in a dictionary "a" comes before "aa" and before "b" etc. So "1" comes before "10" but "100" comes before "2" in the same way that "aa" comes before "b". The solution is to force it to do the comparison as numbers. To do that you use the - operator. To use the - operator with .sort() you do points.sort((a,b) => a - b)Snowslide
M
2

const points = [40, 100, 1, 5, 25, 10];

console.log(points)

console.log(points.sort())

console.log(points.sort(function(a, b){return (a - b);}))

By default, the sort() function sorts values as strings.

However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce incorrect results when sorting numbers.

You can fix this by providing a compare function:

const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b});

Solution

Missend answered 18/6, 2022 at 18:43 Comment(0)
C
0

The purpose of the compare function is to define an alternative sort order.

The compare function should return a negative, zero, or positive value, depending on the arguments.

When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

If the result is negative, a is sorted before b.

If the result is positive, b is sorted before a.

If the result is 0, no changes are done with the sort order of the two values.

Crispin answered 29/1, 2024 at 5:0 Comment(0)
U
-2

Actually, @pradipta_paul is almost right, but here is a more informative version: In my own opinion, the array sorting works like this(I don't think that's the originic one)

class List{
    constructor(...args){
        //blablabla
    }
    //blablabla
    sort(func){
        func=func || function(a,b){return a-b};
        for(let i in this.array){
            this.array_move_to_ind(func(array[i],array[i-1]))
        }
    }
}
Unmanned answered 1/8, 2024 at 13:16 Comment(2)
This seems distinctly less clear than the other answer you mentioned. You appear to be making your own class with some custom sorting logic, not explaining the built-in sort?Obfuscate
Actually, I see that the questioner does not clear about the INSIDE gear of how does javascript works on sorting array, so I show him/her the ropes @ObfuscateSlap

© 2022 - 2025 — McMap. All rights reserved.