This is the second article in The JavaScript Snippet Series. In the previous episode we discussed three methods of getting unique values from JavaScript. In this article, we will discuss various ways of sorting arrays in JavaScript.
Sorting is a common task when working with arrays. It would be used, for instance, if you want to display the city or county names in alphabetical order.
The JavaScript Array object has a built-in method sort() for sorting array elements in alphabetical order. Okay, let's get a move on.
First of all, let us instantiate the variables will be sorted in this article.
const arrCharacters = ["mary", "had", "a", "little", "lamb"];
const arrInteger = [
1,
2,
3,
4,
5,
6,
100,
10,
200,
1,
11,
30,
1000,
500,
700,
900,
];
const arrObject = [
{ name: "asemota" },
{ name: "unicodeveloper" },
{ name: "hacksultan" },
{ name: "developerayo" },
{ name: "wellpaiddeveloper" },
{ name: "sarah_edo" },
{ name: "techgirl1908" },
];
The first variable arrCharacters
is an array of strings, second variable arrCharacters
is an array of numbers and the third variable arrObject
is an array of objects with key-value pairs.
Now let's move on the sorting these variables.
Sorting arrays of strings
We will start with the array of strings. Sorting arrays of strings in JavaScript is pretty straight-forward. All you need to do is call the builtin sort
method on the array.
const sortChar = (arr) => {
return arr.sort();
};
const result = sortChar(arrCharacters);
console.log(result);
As you can see in the image above, this simply sorts the array in ascending order with no fuss and no moss.
Sorting arrays of numbers
Sorting an array of numbers is not as straight forward as sorting an array of strings unfortunately although come to think of it, the extra steps you need to perform are not that difficult.
Let us see what happens when we sort an array of integers like we sort the array of strings above.
const sortIntegerwrong = (arr) => {
return arr.sort();
};
const result = sortIntegerwrong(arrInteger);
console.log(result);
As you can see, the result is different from what we've expected. It happens because the sort() method sorts the numeric array elements by converting them to strings (i.e. 30 becomes "30", 100 becomes "100", and so on), and since the first character of the string "30" (i.e. "3") comes after the first character of the string "100" (i.e. "1"), that's why the value 20 is sorted after the 100.
To fix this sorting problem with a numeric array, you can pass a compare callback, like this:
// Sort Integer Rewritten the first time.
const sortInteger = (arr) => {
return arr.sort((a, b) => {
if (a > b) {
return 1;
} else if (b > a) {
return -1;
} else {
return 0;
}
});
};
const result = sortInteger(arrInteger);
console.log(result);
Now we finally have a well-sorted array. Let's see how it works.
When a callback function is specified, array elements are sorted according to the return value of the callback function. For example, when comparing a and b:
If the callback function returns a value less than 0, then a comes first. If the callback function returns a value greater than 0, then b comes first. If the callback function returns 0, a and b remain unchanged with respect to each other but sorted with respect to all other elements.
There are various ways to implement the callback function in JavaScript as demonstrated below:
// Sort Integer Rewritten the second time. Come on!
const sortIntegerOptionA = (arr) => {
arr.sort((a, b) => {
return a - b;
});
};
const result = sortIntegerOptionA(arrInteger);
console.log(result);
// Sort Integer Rewritten the third time. I promise, this is the final time
const sortIntegerOptionB = (arr) => {
return arr.sort((a, b) => {
return a > b ? 1 : b > a ? -1 : 0;
});
};
const result = sortIntegerOptionB(arrInteger);
console.log(result);
They all produce the same result as above.
Sort an array of objects
An array of objects in JavaScript contains objects of key-value pairs. Sorting these arrays requires the use of a callback method with the built-in sort method. However, you would need to access specific keys to be able to properly sort the arrays based on the values in the object.
// Array of objects of names
const sortArrObject = (arr) => {
return arr.sort((a, b) => {
return a.name > b.name ? 1 : b.name > a.name ? -1 : 0;
});
};
const result = sortArrObject(arrObject);
console.log(result);
What we did here was to use the callback function to check if the value of the name key of each object is greater, less, or equal to the subsequent object. The same logic we used when sorting integers also applies here. The difference is that we have to access the values of the object by the corresponding key.
In this article, we have examined some ways to sort arrays in JavaScript. We will be discussing in details Array.prototype.reduce()
in the next episode of the JavaScript Snippet Series. Hope to see you back here soon.