Say you have an array consisting of objects. And you want to order that array by one of the properties of these objects.
Take this array:
[
{
id: 4,
title: "Lorem ipsum",
created: "2020-04-10T14:59:00+00:00"
},
{
id: 2,
title: "Iptum quanto",
created: "2020-05-29T13:17:48+00:00"
},
{
id: 1,
title: "Dolor samet",
created: "2020-05-29T13:16:20+00:00"
},
{
id: 3,
title: "Tenari fluptum",
created: "2020-05-29T13:08:39+00:00"
}
]
Let’s sort it by the
created
property of each element
const orderedChapters = chapters.sort((a, b) => {
return a.created.localeCompare(b.created))
}
This is the order now
[
{
id: 4,
title: "Lorem ipsum",
created: "2020-04-10T14:59:00+00:00"
},
{
id: 3,
title: "Tenari fluptum",
created: "2020-05-29T13:08:39+00:00"
},
{
id: 1,
title: "Dolor samet",
created: "2020-05-29T13:16:20+00:00"
},
{
id: 2,
title: "Iptum quanto",
created: "2020-05-29T13:17:48+00:00"
}
]