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

javascriptweb developmentfront end technologyobject oriented programming

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

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' }
]

相关文章