Sorting arrays by object properties

By passing a function when sorting an array, we can sort objects by different properties.

const people = [
  { name: 'Lisa',   age: 8  },
  { name: 'Maggie', age: 1  },
  { name: 'Homer',  age: 34 },
  { name: 'Bart',   age: 10 },
  { name: 'Marge',  age: 33 }
]

// sort `people` by name (alphabetically)
people.sort((a, b) => a.name > b.name)
// ⇒ [
//     { name: 'Bart',   age: 10 },
//     { name: 'Homer',  age: 34 },
//     { name: 'Lisa',   age: 8  },
//     { name: 'Maggie', age: 1  },
//     { name: 'Marge',  age: 33 }
//   ]

// sort `people` by age (from oldest to youngest)
people.sort((a, b) => b.age - a.age)
// ⇒ [
//     { name: 'Homer',  age: 34 },
//     { name: 'Marge',  age: 33 },
//     { name: 'Bart',   age: 10 },
//     { name: 'Lisa',   age: 8  },
//     { name: 'Maggie', age: 1  }
//   ]

// sort `people` by name (from longest to shortest)
people.sort((a, b) => a.name.length - b.name.length)
// ⇒ [
//     { name: 'Bart',   age: 10 },
//     { name: 'Lisa',   age: 8  },
//     { name: 'Homer',  age: 34 },
//     { name: 'Marge',  age: 33 },
//     { name: 'Maggie', age: 1  }
//   ]

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.