Sorting arrays by object properties

Posted on

Array.prototype.sort() treats all array values as strings and sorts them alphabetically. By passing a function when sorting an array of objects, we can sort them by one of their 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  }
//   ]
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  }
//   ]
Debug
none
Grid overlay