OneBite.Dev - Coding blog in a bite size

sort javascript array

Code snippet for how to how to sort javascript array with sample and detail explanation

Manipulating data is an integral part of programming, and sorting is an operation that comes up quite frequently. In JavaScript, an array is a single variable used to store different elements, and in this article, we’ll be focusing on how you can sort those elements in an array.

Code snippet for Sorting JavaScript Array

let arr = [34, 23, 3, 76, 20, 84, 18, 9];
arr.sort(function(a, b){return a-b});
console.log(arr);

Code Explanation for Sorting JavaScript Array

In this simple snippet, we first create an array arr with random numbers.

The next step is where the sorting happens. Here we are using the sort() method native to JavaScript arrays. The sort() method does just what its name suggests. It sorts the elements in an array in place and returns the array. It’s important to note that sort() does not make a copy of the array before sorting. It sorts the original array.

The complexity comes when we realize that the sort() method doesn’t exactly sort in the way we humans do. If we leave it to itself, it converts the elements into strings and sorts them by comparing their sequences of UTF-16 Unicode code unit values.

That’s why we are passing a function to the sort(). This function (a, b) => a-b is now in charge of sorting. The function basically tells JavaScript to sort the numbers in ascending order (if you want it to sort in descending order, you’d use (a, b) => b-a). It compares two elements at a time, subtracts one from the other, and then determines which should come first based on whether the result is negative, zero, or positive.

In the last line, we log the now sorted array, which will display the numbers sorted in ascending order.

That’s really all there is to it! This is a simple, yet effective, method to sort numerical arrays in JavaScript. The real beauty of it lies in how customizable it is — by changing the function we pass to sort(), we can easily change how our array gets sorted.

javascript