Javascript-根据多个字段对对象列表进行排序

时间:2020-04-22 15:57:39

标签: javascript sorting

我有以下对象的数组:

[{name : "Mariah" , quantity: 2},
{name : "Vincent" , quantity: 1},
{name :"Albert" , quantity: 1},
{name : "Patrick" , quantity: 1},
{name : "Vincent" , quantity: 2}]

我想先根据数量字段对列表进行排序,然后再根据名称字段按字母顺序排序 像这样

    [{name :"Albert" , quantity: 1},
    {name : "Patrick" , quantity: 1},
    {name : "Vincent" , quantity: 1},
    {name : "Mariah" , quantity: 2},
    {name : "Vincent" , quantity: 2}]

1 个答案:

答案 0 :(得分:-1)

let list = [{name : "Mariah" , quantity: 2},
            {name : "Vincent" , quantity: 1},
            {name :"Albert" , quantity: 1},
            {name : "Patrick" , quantity: 1},
            {name : "Vincent" , quantity: 2}
           ]

let sort = list.sort(function(a,b){
  if (a.quantity != b.quantity){
    return a.quantity - b.quantity
  }else{
    return a.name.localeCompare(b.name)
  }
})

console.log(sort)