Reputation: 63
I'm learning javascript and a I got some questions about the sort method in javascript, yes, before you ask I've read the other questions, I understand this:
"Less than 0: "a" is sorted to be a lower index than "b". Zero: "a" and "b" are considered equal, and no sorting is performed. Greater than 0: "b" is sorted to be a lower index than "a"."
Thats from the main question about the sort() function, but what I don't understand is:
var array=[5, 2, 1, 10]
array.sort(function(a,b) {
return a - b})
What is the purpose of the a
and b
as parameters in the function, what are value for the parameters that are going to be used during the function? It is told to return a-b
but who are going to be a
and b
during the process? I'm not asking for the console.log()
example. If a
and b
are my paremeter how is the function going to work if I am not even passing the value of a
and b
?
In other languages it would be neccesary to pass the values of a
and b
.
Upvotes: -1
Views: 842
Reputation: 324
compareFunction: Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
What you are passing in the array.sort is a function known as the comparator function. What it will do is basically when it will sort your array if will sort it will compare two elements of the array at any given time and sort it according to the implementation details of the provided function.
Lets say you have an array [2 , 4, 3]
Given your sort function will pass elements in the comparators to comparators 2,3
and you return the result 2 - 4
which is -2 and you already know < 0 means the the a elements needs to be on lower that is 2 will come first. it will compare 4 - 3
which is > 0 than means a needs to come after.
The Documentation has all the answers to your questions.
Upvotes: 1