JavaScript · JS Tutorial · Lesson 21
JS Array Sort
sort, reverse and compare functions.
The sort() method sorts an array alphabetically. For numbers you need a compare function.
Example
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const points = [40, 100, 1, 5, 25, 10];
let out = fruits.sort() + "<br>";
out += fruits.reverse() + "<br>";
out += [...points].sort() + " (wrong for numbers)<br>";
out += [...points].sort(function (a, b) { return a - b; }) + " (ascending)<br>";
out += [...points].sort((a, b) => b - a) + " (descending)<br>";
const cars = [{ type: "Volvo", year: 2016 }, { type: "Saab", year: 2001 }, { type: "BMW", year: 2010 }];
cars.sort((a, b) => a.year - b.year);
out += cars.map(c => c.type + " " + c.year).join(", ");
document.getElementById("demo").innerHTML = out;
</script>
Tip: Use
toSorted() to get a sorted copy without changing the original array.Keep reading “JS Array Sort”
Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.