Reputation: 151
I have an array of objects. I want to sort the array according to the object key. For example below -
{
"id": 3511,
"time": "03:30",
"hour": 3,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
},
{
"id": 3514,
"time": "04:30",
"hour": 4,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
},
{
"id": 3513,
"time": "04:00",
"hour": 4,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
},
I want to sort it according to time like this-
{
"id": 3511,
"time": "03:30",
"hour": 3,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
},
{
"id": 3513,
"time": "04:00",
"hour": 4,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
},
{
"id": 3514,
"time": "04:30",
"hour": 4,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
},
I have used this function to sort but it is not giving the expected output I have also used the time key, still the same.
timeSlots.sort(function(a, b) {
return a.time- b.time;
});
But not getting an expected output.
Upvotes: 0
Views: 851
Reputation: 29
Your can pass a compare function to sort
method saying how you want to sort the array elements. Thus, it provides a way to sort objects too.
To sort in ascending order:
const sortedArrayOfObjects = array.sort((item1, item2) => {
if(item1.id < item2.id) return -1
else if(item1.id > item2.id) return 1
else return 0;
});
compareFunction(a, b)
returns less than 0, sort a
to an index lower than b
(i.e. a
comes first).compareFunction(a, b)
returns 0, leave a
and b
unchanged with respect to each other, but sorted with respect to all different elements.compareFunction(a, b)
returns greater than 0, sort b
to an index lower than a
(i.e. b
comes first).Upvotes: 0
Reputation: 215
let arr = [{
"id": 3511,
"time": "03:30",
"hour": 3,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
},
{
"id": 3514,
"time": "04:30",
"hour": 4,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
},
{
"id": 3513,
"time": "04:00",
"hour": 4,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
}]
sortedArr = arr.sort(function(a, b){
if (a['time'] < b['time']) return -1;
if (a['time'] > b['time']) return 1;
return 0
})
console.log(`sorted: `, sortedArr);
Upvotes: 0
Reputation: 4554
Lodash's "sortBy
" is perfect for this.
_.sortBy(timeSlots, 'time');
Upvotes: 1
Reputation: 147206
Since your .time
values are in HH:MM
format, you can sort them as strings:
let array = [{
"id": 3511,
"time": "03:30",
"hour": 3,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
},
{
"id": 3514,
"time": "04:30",
"hour": 4,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
},
{
"id": 3513,
"time": "04:00",
"hour": 4,
"utc_date_time": "2020-07-07T02:07:54.000Z",
"members": 0
}
];
array.sort((a, b) => a.time.localeCompare(b.time));
console.log(array);
Upvotes: 3