sort by multiple keys

let votes = [
    { title: 'Apple', votes: 1 },
    { title: 'Milk', votes: 2 },
    { title: 'Carrot', votes: 3 },
    { title: 'Banana', votes: 2 }
];

// ⭐️ 一行搞定,真是天才❗️
let sorted = votes.sort((a,b) => 
    // 1. 先排 votes (多的人先)
    // 2. 再排 title (按字母順序)
    b.votes - a.votes || a.title.localeCompare(b.title)
);

/*
[
  { title: 'Carrot', votes: 3 },
  { title: 'Banana', votes: 2 },
  { title: 'Milk'  , votes: 2 },
  { title: 'Apple' , votes: 1 }
]
*/

Last updated

Was this helpful?