How to Sort an Array of Integers in JavaScript
-
Sort an Array of Integers in JavaScript Using the
.sort
Method - Passing a Compare Function as Parameter
- Sort an Array of Integers in JavaScript Using the Arrow Function
Introducing the .sort
method that can be used to sort an array by specific order, this tutorial has the purpose of explaining why this method needs a comparison function if you want to sort an array of integer numbers correctly.
This comparison function will dictate the sorting order. Also, we will explain how to use it to make a descending order sorting, plus a shorter way to use it all together, by utilizing the comparison function as an Arrow Function within the .sort
method.
Sort an Array of Integers in JavaScript Using the .sort
Method
The .sort
method is a method of the Array
entity that returns an ordered array from the array that this method was originally called. For example:
// Input
let array = [10, 10000, 1000, 100, 1]
console.log(array.sort())
Output:
// Output
[ 1, 10, 100, 1000, 10000 ]
Sure, this is expected as the .sort
method orders the array. But, if we have the below input:
// Input
let array = [12900, 877, 12, 992, 10000]
console.log(array.sort())
We have a wrong ordering like this:
// Output
[10000, 12, 12900, 877, 992]
It happens because .sort
default order is based on the UTF-16
or 16-bit Unit Transformation Format
, which is an encoding of the Unicode pattern. The method converts the array values into the string type and then orders their Unicode values.
With this explained, the .sort
method can also be used to order other data types, not only numbers.
But how can the .sort
method be used to order an array correctly? It is simple: by using a Compare Function.
Passing a Compare Function as Parameter
As the .sort
method can be used without any parameter, a Compare Function is optional. Basically, this function defines the .sort
method ordering, and this function receives two parameters: the first element to be compared and the second element to be compared.
The .sort
method will:
- Put
first
aftersecond
if thecompareFunction
return a value greater than 0; - Put
first
beforesecond
if thecompareFunction
return a value less than 0; - Do nothing if the
compareFunction
return a value equals to 0.
So, with the compareFunction(first, second)
, we can dictate the order of the sort by passing an operation among the first
and second
parameters. To ascending ordering,
// Ascending ordering
function compareFunction(first, second) {
if (first > second)
return 1 // 1 is greater than 0, so .sort will put first after second.
if (first < second) return -1 // -1 is less than 0, so .sort will put first
// before second.
return 0
}
And for descending order, we can invert the operators.
// Descending ordering
function compareFunction(first, second) {
if (first < second)
return 1 // 1 is greater than 0, so .sort will put first after second.
if (first > second) return -1 // -1 is less than 0, so .sort will put first
// before second.
return 0
}
Now, putting compareFunction
for ascending ordering together with the .sort
method, finally, we have:
// Input:
let array = [12900, 877, 12, 992, 10000]
// Ascending
array.sort(function compareFunction(first, second) {
if (first > second)
return 1 // 1 is greater than 0, so .sort will put first before second.
if (first < second) return -1 // -1 is less than 0, so .sort will put first
// after second.
return 0
})
console.log(array)
Output:
// Output:
[ 12, 877, 992, 10000, 12900 ]
Sort an Array of Integers in JavaScript Using the Arrow Function
We can also reduce all the code block to a minimum syntax, utilizing Arrow functions.
An Arrow function is another way to use a function with shorter syntax. Arrow Functions are anonymous functions, and this means that they are not named (are stored in variables or passed as function parameters) and can’t be used in all situations.
With the structure of an Arrow Function, the traditional functions can be transformed into a shorter block, as the example:
// Common anonymous function
function(x) {
return x + 1;
}
// Arrow function
(x) => x + 1
Besides that, the structure of an Arrow Function can return automatically the expression value without the reserved word return
:
// Arrow function
let arrowFunction = (x) => x + 1
console.log(arrowFunction(1))
Output:
//Output
2
The console.log()
prints the value of 1 + 1
, that is 2
even though the arrowFunction
does not utilize the return
statement. It will help us in the next step.
As said, the .sort
method can have a Compare Function within it, and this function can be an Arrow Function. Converting the previously Compare Function structure, we can transform all that block of code to a shorter block as below:
// Input:
let array = [10000, 10, 100, 1000, 1]
array.sort((first, second) => {
if (first > second) return 1
return -1
})
// Ascending: If first > second == true, then change one by the other.
console.log(array)
We can drop the condition to first < second
and instead, return a -1
value as default if the primary condition is not the case; given that the 0
value to the .sort
method is to equal values and this way, they can have their positions changed without interfering in the final result. This way, we can reduce even more, as the example below:
// Input:
let array = [10000, 10, 100, 1000, 1]
array.sort((first, second) => first > second ? 1 : -1)
// Ascending: If first > second == true, then change one by the other.
console.log(array)
Look that the previous >
comparison and default return
was changed to only one comparison: first > second ? 1 : -1
. It means that if the comparison is true
, it returns 1
; if not, it returns -1
.
We need the ?
ternary operator because the first > second
comparison results only in true
or false
. But as said, the .sort
method expects 1
, -1
or 0
.
Output:
// Output:
[ 1, 10, 100, 1000, 10000 ]
And for descending ordering:
// Input:
let array = [10000, 10, 100, 1000, 1]
array.sort((first, second) => first < second ? 1 : -1)
// Descending: If first < second == true, then change one by the other.
console.log(array)
Output:
// Output:
[ 10000, 1000, 100, 10, 1 ]
Another way to do the same is using the -
ternary operator for subtraction. When we use array.sort((first, second) => first > second ? 1 : -1)
, if first - second
result in a value greater than 0, then will be an index changing among each other. If first - second
result in a value less than 0, nothing will happen, and for equal values, the comparison will return 0
.
Example:
// Input:
let array = [10000, 10, 100, 1000, 1]
console.log(array.sort((first, second) => first - second))
Output:
// Output:
[ 1, 10, 100, 1000, 10000 ]
What can we do in descending order? No, it is not changing the -
ternary operator to +
because each positive number plus another positive number result in a value greater than 0. But we have a simple solution to this: invert the first - second
to second - first
.
This way, if second - first
results in a value greater than 0, then the .sort method will change their positions with each other.
Example:
// Input:
let array = [10000, 10, 100, 1000, 1]
console.log(array.sort((first, second) => second - first))
Output:
// Output:
[ 10000, 1000, 100, 10, 1 ]
Related Article - JavaScript Array
- How to Check if Array Contains Value in JavaScript
- How to Create Array of Specific Length in JavaScript
- How to Convert Array to String in JavaScript
- How to Remove First Element From an Array in JavaScript
- How to Search Objects From an Array in JavaScript
- How to Convert Arguments to an Array in JavaScript