Today we’re going to look at how to sort arrays (and numbered arrays) in JavaScript. Finally, we’ll see how to sort arrays containing objects by adding an attribute, such as priority or order, to display these objects in the desired order.
Array.prototype.sort() is a comparison function used to sort elements of an array.
The arguments of this function are:
compareFunction(a, b) < 0: a comes before b
compareFunction(a, b) > 0: b comes before a
compareFunction(a, b) = 0: the order of a and b is identical.
Examples (descending and ascending sorting):
// sort in descending order
array.sort((a, b) => b – a);
console.log(array);
// sort in ascending order
array.sort((a, b) => a – b);
console.log(array);
Excellent happy coding! 💫
👉 See my other projects on GitHub https://github.com/pH-7 💡
Would you like me to explain or break down the code?