How to sort correctly arrays in JavaScript?


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 beforeb
compareFunction(a, b) > 0:
b
comes beforea
compareFunction(a, b) = 0: the order of
a
andb
is identical.
Examples (descending and ascending sorting):
Descending
const array = [1, 20, 8, 15, 25, 80, 100, 200];
// sort in descending order
array.sort((a, b) => b - a);
console.log(array);jav
Ascending
const array = [1, 20, 8, 15, 25, 80, 100, 200];
// sort in ascending order
array.sort((a, b) => a - b);
console.log(array);
Happy, happy coding! ⚡️
👉 See my other projects on GitHub https://github.com/pH-7 💡
Subscribe to my newsletter
Read articles from Pierre-Henry Soria directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Pierre-Henry Soria
Pierre-Henry Soria
I'm Pierre-Henry Soria. A passionate full stack engineer, building things that matter, making a real impact on the world. Really like to take care of others and manage my workflow based on productivity methodologies. Open to fast-paced changes with rapidly evolving business and technologies. I'm always thirsty to learn and undertake new exciting things and thrilling challenges.