If you want to sort an array of objects, call the sort()
method and pass a comparison function to it. Inside the comparison function, access that property of an object whose value is of type Date
. Then call the getTime()
method to get the milliseconds version of the date. After that, return 1 when the first argument is greater than the second and return -1 when the first argument is less than the second.
Let's understand the entire process of sorting an array of objects with the help of an example:
Suppose you have an inventory of products, and each product is stored as an object. If you want to sort this inventory by date, then execute the following code:
let inventory = [ { name: 'Green Floral Midi Dress', id: 823, price: '$45', fabric: 'Polyester', dateOfAdding: new Date(2022, 2, 10) }, { name: 'Blue Ripped Jeans', id: 743, price: '$29.99', type: 'High Waist', dateOfAdding: new Date(2021, 11, 25) }, { name: 'Pink Satin Sleveless Dress', id: 803, price: '$33', fabric: 'Polyester', dateOfAdding: new Date(2022, 1, 27) } ]; inventory.sort((a, b)=>{ if(a.dateOfAdding.getTime() > b.dateOfAdding.getTime()){ return 1; }else if(a.dateOfAdding.getTime() < b.dateOfAdding.getTime()){ return -1 }else{ return 0; } }); console.log(inventory);
Output
[{ name: "Blue Ripped Jeans", id: 743, price: "$29.99", type: "High Waist", dateOfAdding: Sat Dec 25 2021 }, { name: "Pink Satin Sleveless Dress", id: 803, price: "$33", fabric: "Polyester", dateOfAdding: Sun Feb 27 2022 }, { name: "Green Floral Midi Dress", id: 823, price: "$45", fabric: "Polyester", dateOfAdding: Thu Mar 10 2022 }]
Here is the explanation of the code:
1. The products are stored as an array of objects.
let inventory = [ { name: 'Green Floral Midi Dress', id: 823, price: '$45', fabric: 'Polyester', dateOfAdding: new Date(2022, 2, 10) }, { name: 'Blue Ripped Jeans', id: 743, price: '$29.99', type: 'High Waist', dateOfAdding: new Date(2021, 11, 25) }, { name: 'Pink Satin Sleveless Dress', id: 803, price: '$33', fabric: 'Polyester', dateOfAdding: new Date(2022, 1, 27) } ];
2. Since we want to sort the array by date, we must pass the comparison function to the sort()
method. There is a set of rules that you must adhere to if you want to sort using the comparison function:
a. If you want to sort in ascending order, then return 1 when the first argument is greater than the second argument and return -1 when the first argument is less than the second argument.
arr.sort((a, b) => { if(a > b){ return 1; }else if(a < b){ return -1; }else{ return 0; } });
b. On the other hand, if you want to sort in descending order, then return -1 when the first argument is greater than the second one and return 1 when the first argument is less than the second one.
arr.sort((a, b) => { if(a > b){ return -1; }else if(a < b){ return 1; }else{ return 0; } });