Sort an Array of Objects by Key or Value in JavaScript (with Examples)
Introduction
Sorting is one of the fundamental techniques a developer should know. It uses different tools and technologies in people’s daily lives. Some common examples where you will find sorting to exist is on online shopping platforms where the functionality of sorting by price, sorting by ratings, sorting by the date the product has arrived on the forum, and so on is available.
JavaScript Objects
In JavaScript, a very interesting datatype is called an ‘object.’ It offers ease of development by providing a “key-value” model which enables you to store your data with clearly labeled variables corresponding to a specific user/entity.
const iceCreams = {
flavor:"strawberry",
price:15.00,
popularityScore:200
}
console.log(iceCreams);
Code language: JavaScript (javascript)
View this code snippet in objects.js in Codedamn Playground.
This object called iceCreams has three properties or three key-value pairs. The keys for the object iceCreams involve flavor, price, and popularityScore. The data type for these is string, float, and int, respectively. The values for these keys are “strawberry,” 15.00, and 200, respectively.
JavaScript Arrays
Readers who are familiar with basic programming constructs would know about arrays. If we wish to reiterate the same concept, an array is a collection of homogenous elements. By homogeneous, it is meant that elements have the same data type. Arrays are helpful when you, as a developer, need to store elements in a list-like format and want to access them sequentially or by their index number. The index number is the position of the element in the array. 0-based indexing is followed in JavaScript arrays, meaning that the first element in the array will start from an index number 0.
const iceCreamArray = [
"strawberry",
"vanilla",
"chocolate"
]
console.log(iceCreamArray);
Code language: JavaScript (javascript)
View this code snippet in arrays.js in Codedamn Playground
This is an array called iceCreamArray, which has three elements – “strawberry,” “vanilla,” and “chocolate,” which are all of the string data types. If we wish to access the elements of the array, square brackets are used with index numbers written in between.
//access the 1st element of the array
console.log(iceCreamArray[0]);
//access the 2nd element of the array
console.log(iceCreamArray[1]);
//access the 3rd element of the array
console.log(iceCreamArray[2]);
Code language: JavaScript (javascript)
View this code snippet in arrays.js in Codedamn Playground
JavaScript Array of Objects
If an array is a collection of homogenous elements and an object is an element, is there a possibility of an array of objects? Absolutely!
let iceCreams = [
{
flavor:"chocolate",
price:10,
popularityScore:100
},
{
flavor:"strawberry",
price:15,
popularityScore:200
},
{
flavor:"vanilla",
price:5,
popularityScore:50
},
{
flavor:"butterscotch",
price:20,
popularityScore:150
}
]
Code language: JavaScript (javascript)
View this code snippet in index.js in Codedamn Playground
This is an array of iceCream objects. Each element of this array contains an object with three keys – flavor, price, and popularity score. Flavor is of the type string, price is of the type float, and popularity score is of the type integer.
Sorting Array of Objects in JavaScript
Sorting IceCreams Array of Objects By Price
//sorting by price in Ascending order
let sortPriceAsec = () => iceCreams.sort((iceCream1,iceCream2)=>{
return iceCream1.price - iceCream2.price;
})
//sorting by price in Descending order
let sortPriceDesec = () => iceCreams.sort((iceCream1,iceCream2)=>{
return iceCream2.price - iceCream1.price;
})
Code language: JavaScript (javascript)
If we wish to sort the iceCreams array of objects by price, there are two methods – one in ascending order and one in descending order.
We are aware of the fact that the sort() function, when provided with a negative value, puts the first element before the second element, when provided with a positive element, puts the second element before the first element, and, when provided with 0 doesn’t make any swaps.
Therefore, to sort the array of objects by the value of price, we need to come up with a way that a negative or positive value is returned.
Here is the intuition:
- When we are comparing 5.00 and 10.00, we want 5.00 to come before 10.00. In order to do the same, we need the sort() function to return a negative value. We can obtain the same by subtracting 10.00 from 5.00.
- When we are comparing 15.00 and 10.00, we want 15.00 to come after 10.00. In order to do the same, we need the sort() function to return a positive value. We can obtain the same by subtracting 10.00 from 15.00.
Therefore we observe that if we subtract one price amount from the other if a negative value is returned, it means the first element is lesser than the second element, and the first element will be placed before the second element. Similarly, if a positive value is returned, then it means the second element is lesser than the first element, and the first element will be placed after the second element. In descending order, this will be done in a vice-versa manner.
Hence we conclude:
- To sort in the ascending order, we have to return a negative value if the first element is lesser than the second element and return a positive value if the first element is greater than the second element.
- To sort in the descending order, we have to return a positive value if the first element is lesser than the second element and return a negative element if the first element is greater than the second element.
Sorting IceCreams Array of Objects By Flavor
//sort by flavor in Ascending order
let sortFlavorAsec = () => iceCreams.sort((iceCream1,iceCream2)=>{
let iceCreamFlavor1 = iceCream1.flavor;
let iceCreamFlavor2 = iceCream2.flavor;
if(iceCreamFlavor1<iceCreamFlavor2){
return -1;
}
if(iceCreamFlavor1>iceCreamFlavor2){
return 1;
}
return 0;
})
//sort by flavor in Descending order
let sortFlavorDesec = () => iceCreams.sort((iceCream1,iceCream2)=>{
let iceCreamFlavor1 = iceCream1.flavor;
let iceCreamFlavor2 = iceCream2.flavor;
if(iceCreamFlavor1<iceCreamFlavor2){
return 1;
}
if(iceCreamFlavor1>iceCreamFlavor2){
return -1;
}
return 0;
})
Code language: JavaScript (javascript)
If we wish to sort the iceCreams array of objects by flavor, there are again two methods – one in ascending order and one in descending order. This technique is applicable to all values of the string type.
As we discussed while sorting the array elements by the price value, we need to return a negative value in the comparator function provided to the sort in order to place the first element before the second element, and we need to return a positive value in the comparator function in order to place the first element after the second element.
But how do we apply the same for string elements? When we compare two strings, JavaScript essentially compares the lexicographical order of the first character of the strings.
Here is the intuition with the example of strings “vanilla”, “strawberry” and “butterscotch”:
- Our first string is “vanilla” and our second string is “strawberry”. Now if we want that “vanilla” should come after “strawberry”, the comparator function should return a positive value.
- Our first string is “butterscotch” and our second string is “vanilla”. Now if we want that “butterscotch” should come before “vanilla” the comparator function should return a negative value.
- Hence, to sort in ascending order, if the first string is greater than the second string a positive value should be returned and if the first string is lesser than the second string a negative value should be returned.
- And to sort in descending order, if the first string is greater than the second string, a negative value should be returned and if the first string is lesser than the second string a positive value should be returned.
Summary
In the above article, we understood what sorting is, what objects and arrays in JavaScript are, what it means by an array of objects, and finally, how to sort an array of objects with either a numerical or a string data type. The intuition of the same has been thoroughly discussed. Readers are encouraged to dry-run the intuition on paper to enable them to understand the concept by heart.
Learn the basics of JavaScript with Codedamn here.
Happy Learning!
Sharing is caring
Did you like what Pooja Gera wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: