假设我们有一个像这样的对象数组-
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' } ]