以升序对关联数组进行排序 - JavaScript


假设我们有一个这样的对象数组 −

const people = [
   {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"},
   {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
   {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
   {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"}  
];

我们需要编写一个 JavaScript 函数,该函数接收这样的数组,并根据每个对象中 age 属性的升序对数组就地进行排序。

因此,输出应如下所示 −

const output = [
   {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
   {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
   {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"},
   {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"}
];

范例

以下是完整代码 −

const people = [
   {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"},
   {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
   {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
   {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"}
];
const sorter = (a, b) => {
   return a.age - b.age;
};
const sortByAge = arr => {
   arr.sort(sorter);
};
sortByAge(people);
console.log(people);

输出

这将在控制台输出以下内容 −

[
   { id: 3, name: 'Christine', age: 20, gender: 'm', category: 'G' },
   { id: 2, name: 'Brandon', age: 25, gender: 'm', category: 'G' },
   { id: 4, name: 'Elena', age: 29, gender: 'W', category: 'M' },
   { id: 1, name: 'Andrew', age: 30, gender: 'm', category: 'G' }
]

更新于: 30-Sep-2020

1 千次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告