How to sort an array of objects in JavaScript

Arrays in JavaScript come with a built-in function that is​ used to sort elements in alphabetical order.

However, this function does not directly work on arrays of numbers or objects. Instead a custom function, that can be passed to the built-in sort() method to sort objects based on the specified property, is needed for comparison.

svg viewer

Sorting techniques

1. Using a custom sort function.

Note that the arguments of compare_item() and compare_qty() are elements of the array (i.e. objects in the above case). Hence, the . operator was used to specify the property on which the array cart had to be sorted.

However, creating compare functions for all the properties, based on which array can be sorted, results in a lot of repetitive code. Here is where the technique, which will be discussed next, comes to the rescue.

// Comparing based on the property item
function compare_item(a, b){
// a should come before b in the sorted order
if(a.item < b.item){
return -1;
// a should come after b in the sorted order
}else if(a.item > b.item){
return 1;
// and and b are the same
}else{
return 0;
}
}
//Comparing based on the property qty
function compare_qty(a, b){
// a should come before b in the sorted order
if(a.qty < b.qty){
return -1;
// a should come after b in the sorted order
}else if(a.qty > b.qty){
return 1;
// a and b are the same
}else{
return 0;
}
}
cart = [{item: "Berry", qty: 1},
{item: "Apple", qty: 2},
{item: "Kiwi", qty: 3}];
console.log("Object to be sorted");
console.log(cart);
console.log("Sorting based on the item property");
console.log(cart.sort(compare_item));
console.log("Sorting based on the qty property");
console.log(cart.sort(compare_qty));

2. Using a custom, dynamic sort function

Notice that, to flip the rules that have been defined for sorting in ascending order, the sort_order variable is set to -1. Hence, the function now sorts in descending order.

function dynamicsort(property,order) {
var sort_order = 1;
if(order === "desc"){
sort_order = -1;
}
return function (a, b){
// a should come before b in the sorted order
if(a[property] < b[property]){
return -1 * sort_order;
// a should come after b in the sorted order
}else if(a[property] > b[property]){
return 1 * sort_order;
// a and b are the same
}else{
return 0 * sort_order;
}
}
}
cart = [{item: "Berry", qty: 2},
{item: "Apple", qty: 1},
{item: "Kiwi", qty: 3}];
console.log("Object to be sorted");
console.log(cart);
console.log("Sorting based on the item property")
console.log(cart.sort(dynamicsort("item","desc")));
console.log("Sorting based on the qty property")
console.log(cart.sort(dynamicsort("qty","asc")));

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved