How to Perform Sorting of Numbers in Javascript

When you ask how to sort numbers in Javascript, the first method that comes to mind is Array.sort() right? Well that’s the most popular one sure. But there are more methods that developers make use of depending on the need of the hour. Let’s delve into other types of sorting methods available in Javascript as well after taking a look at the sort() method that the language provides.

Excuse the Hogwarts Joke!

Sorting is a fundamental operation in programming, and JavaScript provides powerful tools to help you arrange numerical data efficiently. Let’s explore various methods for sorting numbers in JavaScript, ensuring that you have the right tools at your disposal to organize numerical data with ease.

Take a look at all the methods that will help you get sorted 😀

Different Ways to Perform Sorting of Numbers in Javascript

Array.sort() Method:

JavaScript’s built-in Array.sort() method is a versatile and convenient way to sort elements in an array. By default, it converts elements to strings and compares their sequences of UTF-16 code units. However, when dealing with numbers, you need to provide a compare function to achieve numerical sorting correctly.

let numbers = [5, 2, 9, 1, 5, 6]; 
numbers.sort(function(a, b) { return a - b; });
console.log(numbers);

In this example, the compare function subtracts b from a, resulting in ascending numerical order. To sort in descending order, swap a and b.

The output you will get would of course come out as sorted:

[ 1, 2, 5, 5, 6, 9 ]

So the descending order sort would look like:

console.log(numbers.sort(function (a,b) {return b-a}));

That’s it!

Sorting without Mutation:

If you want to preserve the original array, you can create a new array and sort it:

let originalArray = [5, 2, 9, 1, 5, 6]; 
let sortedArray = [...originalArray].sort((a, b) => a - b); 
console.log(sortedArray);

This way, the originalArray remains unchanged, and you have a sorted version in sortedArray.

Sorting an Object Array:

If you’re working with an array of objects containing numeric properties, you can customize the compare function to sort based on a specific property.

let objectsArray = [ { id: 3, value: 10 }, { id: 1, value: 5 }, { id: 2, value: 8 } ]; objectsArray.sort((a, b) => a.value - b.value); 
console.log(objectsArray);

Here, the array is sorted based on the ‘value’ property of the objects.

Sorting an Object:

Let us say we have just an object and not an array. But we want an array as an output. How do you sort it based on the key and value?

Well, you could use Object.entries() method to get that done.

let list = {
"Kiral": 42,
"Maneja": 79,
"Zygie": 68,
"Theodore": 24
};

console.log(Object.entries(list).sort((a,b) => a[1]-b[1]));

The above will give you the result based on value in this case will do number sorting.

The output would be:

[
[ 'Theodore', 24 ],
[ 'Kiral', 42 ],
[ 'Zygie', 68 ],
[ 'Maneja', 79 ]
]

Now if you want it in decreasing order, simply make the function as b[1]-a[1]. That’s it:

console.log(Object.entries(list).sort((a,b) => b[1]-a[1]));

The result you will get is:

[
[ 'Maneja', 79 ],
[ 'Zygie', 68 ],
[ 'Kiral', 42 ],
[ 'Theodore', 24 ]
]

Sorting with a Custom Comparator:

For more complex sorting criteria, you can use a custom comparator function:

let customSort = function(a, b) { // Your custom comparison logic here };letcustomSortedArray = originalArray.sort(customSort); 
console.log(customSortedArray);

This approach allows you to implement sorting based on unique requirements.

Conclusion On Sorting on Numbers in Javascript

Sorting numbers in JavaScript is a straightforward process, thanks to the versatile Array.sort() method. By understanding how to use compare functions, you can tailor the sorting process to your specific needs. Whether you’re working with simple numeric arrays or arrays of objects with numeric properties, JavaScript provides the tools to organize your data efficiently. Experiment with these methods to discover the most suitable approach for your particular use case.

If you like the above tutorial on How to Perform Sorting of Numbers in Javascript feel free to check out more JS tutorials.
Learn more in Javascript.

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

Leave a Reply