对象数据排序数组

时间:2019-02-01 23:15:38

标签: javascript arrays sorting object

我无法正确排序数据

var persons = [
    { name: 'Marsh', age: 31 },
    { name: 'Amanda', age: 12 },
    { name: 'Mike', age: 33 },
    { name: 'Rachel', age: 30 },
    { name: 'Arnold' },
    { name: 'Pradesh', age: 23 }
];

// persons.sort(); -> does not do anything    
console.log(persons.sort(function(a, b) {
    return a.age > b.age;
}));
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

提供输出

[ { name: 'Amanda', age: 12 },
  { name: 'Rachel', age: 30 },
  { name: 'Marsh', age: 31 },
  { name: 'Mike', age: 33 },
  { name: 'Arnold' },
  { name: 'Pradesh', age: 23 } ]

,预期结果应该是

[ { name: 'Amanda', age: 12 },
  { name: 'Pradesh', age: 23 },
  { name: 'Rachel', age: 30 },
  { name: 'Marsh', age: 31 },
  { name: 'Mike', age: 33 },
  { name: 'Arnold' } ]

我如何修改代码以实现这一目标

0 个答案:

没有答案