Aditya
Aditya

Reputation: 1274

Numeric Sort in JavaScript

I want to sort an array of numerical values and I find a code likes :

<!DOCTYPE html>
<html>
<body>

<p>Click the button to sort the array in ascending order.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;    

function myFunction() {
    points.sort(function(a, b){return a-b});
    document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

Output:

1,5,10,25,40,100

The code runs properly but I can't understand how the statement points.sort(function(a, b){return a-b});is working and what is a and b?

Upvotes: 0

Views: 574

Answers (3)

Vyacheslav Pukhanov
Vyacheslav Pukhanov

Reputation: 1928

Array.sort is a function, which takes compare function as a parameter.

When sorting, sort function calls that compare function, passing in two elements of an array being sorted.

  • If this function returns value, which is less than zero, than first element should stay left from the second.

  • If it returns number, which is greater than zero, than first element should stay right from the second (in sorted array)

  • If it returns zero, than these elements are equal and it doesn't matter in which order they stay.

So to change the order of sort (if you need), you can just switch the compare function to

return b - a;

Upvotes: 1

V31
V31

Reputation: 7666

a and b are numbers in the array which are compared with each other,

Hence if a-b comes out to be negative then it signifies that b>a so if the list is ascending it will put a ahead of b

As per Mozilla Docs

If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

If compareFunction(a, b) is greater than 0, sort b to a lower index than a. compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments.

If inconsistent results are returned then the sort order is undefined

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

This would be easy to understand:

if(a < b){
  return -1;
} else if( a > b){
  return 1;
} else { 
  return 0;
}

Upvotes: 0

Related Questions