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