Tag Archives forjavascript

Sort an array in javascript by property of one of the object elements

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 string created property of each element

const orderedChapters = chapters.sort((a, b) => {
  return a.created.localeCompare(b.created))
}

OR sort it by the numerical id property of each element

const orderedChapters = chapters.sort((a, b) => {
  return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0)
}