Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

The Compare Function

The compare function serves to establish an alternative sorting sequence.

It should return a negative, zero, or positive value based on the comparison of the arguments.

function(a, b){return a – b}

During the sorting process, the sort() function evaluates two values by passing them to the compare function. It then arranges the values based on 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, the sort order of the two values remains unchanged.

Example:

The compare function compares array values in pairs (a, b), and when 40 and 100 are compared, a - b returns a negative value, placing 40 before 100. This approach works for both numerical and alphabetical sorting.

<button onclick=”myFunction1()”>Sort Alphabetically</button>
<button onclick=”myFunction2()”>Sort Numerically</button>

<p id=”demo”></p>

<script>
const points = [40100152510];
document.getElementById(“demo”).innerHTML = points;

function myFunction1() {
  points.sort();
  document.getElementById(“demo”).innerHTML = points;
}

function myFunction2() {
  points.sort(function(a, b){return a – b});
  document.getElementById(“demo”).innerHTML = points;
}
</script>