April 19, 2021
Sorting by array position
This is a nice little JS trick I use quite often, let’s say you got an array of objects such as
const classes = [
{
name: 'CS101',
weekday: 'Friday',
},
{
name: 'CS349F',
weekday: 'Wednesday',
},
{
name: 'CS377E',
weekday: 'Tuesday',
},
{
name: 'CS390D',
weekday: 'Thursday',
},
{
name: 'CS294D',
weekday: 'Monday',
},
{
name: 'CS294S',
weekday: 'Friday',
},
{
name: 'CS802',
weekday: 'Wednesday',
},
]
and you want to sort it by weekday. What you can do is define your desired order in an array like
const WEEKDAY_ORDER = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
]
and then you can use indexOf
to sort by array indices:
classes.sort(
(c1, c2) =>
WEEKDAY_ORDER.indexOf(c1.weekday) - WEEKDAY_ORDER.indexOf(c2.weekday)
)