To sort an array of numbers
in JavaScript, you can use the sort()
method on the array object.
Sort the array in ascending order
To sort the numbers
array in ascending order, you have to pass a function to the sort()
method to customize its behavior, and the function will be passed 2 elements a
and b
while iterating.
You have to subtract a-b
and return the result.
// array of numbers
const numArr = [34, 56, 78, 90, 4, 5, 6, 34];
// sort array
// in ascending order
numArr.sort((a, b) => {
return a - b;
});
console.log(numArr); // [4, 5, 6, 34, 34, 56, 78, 90]
Here a
is the second element of the current iteration and b
is the first element of the current iteration.
If the result of the subtraction is a negative number, then the numbers are swapped and the array contains numbers in ascending order.
See this example live in JSBin.
Sort the array in descending order
To sort the numbers
array in ascending order, you have to pass a function to the sort()
method to customize its behavior, and the function will be passed 2 elements a
and b
while iterating.
You have to subtract b-a
and return the result.
// array of numbers
const numArr = [34, 56, 78, 90, 4, 5, 6, 34];
// sort array
// in descending order
numArr.sort((a, b) => {
return b - a;
});
console.log(numArr); // [90, 78, 56, 34, 34, 6, 5, 4]
Here a
is the second element of the current iteration and b
is the first element of the current iteration.
If the result of the subtraction is a negative number, then the numbers are swapped and the array contains numbers in descending order.
See this example live in JSBin.
Some resources if you want to get more information on using various sorting algorithms in JavaScript:
Bubble sort algorithm in JavaScript
Insertion sort algorithm in JavaScript
Selection sort in JavaScript
Merge Sort in JavaScript
Radix sort in JavaScript
Bucket sort in javascript
Shell sort in JavaScript
Heap sort in JavaScript
Counting sort in JavaScript