JavaScripts数组里的对象排序的24个方法
在JavaScript中,有许多方法可以用于对数组中的对象进行排序。以下是24种排序方法的示例代码:
- 使用Array.prototype.sort()和Object.values()
let arr = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 21 }
];
arr.sort((a, b) => a.age - b.age);
console.log(arr);
- 使用Array.prototype.sort()和Object.values(),按年龄降序排序
let arr = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 21 }
];
arr.sort((a, b) => b.age - a.age);
console.log(arr);
- 使用lodash的\_.orderBy()
const _ = require('lodash');
let arr = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 21 }
];
arr = _.orderBy(arr, 'age', 'asc');
console.log(arr);
- 使用lodash的\_.orderBy(),按年龄降序排序
const _ = require('lodash');
let arr = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 21 }
];
arr = _.orderBy(arr, 'age', 'desc');
console.log(arr);
- 使用Ramda的R.sort()
const R = require('ramda');
let arr = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 21 }
];
arr = R.sort(R.ascend(R.prop('age')), arr);
console.log(arr);
- 使用Ramda的R.sort(),按年龄降序排序
const R = require('ramda');
let arr = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 21 }
];
arr = R.sort(R.descend(R.prop('age')), arr);
console.log(arr);
- 使用Lodash的\_.sortBy()
const _ = require('lodash');
let arr = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 21 }
];
arr = _.sortBy(arr, 'age');
console.log(arr);
- 使用Lodash的\_.sortBy(),按年龄降序排序
const _ = require('lodash');
let arr = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 21 }
];
arr = _.sortBy(arr, [o => -o.age]);
console.log(arr);
- 使用Ramda的R.sortBy()
const R = require('ramda');
let arr = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 21 }
];
arr = R.sortBy(R
评论已关闭