我有一个具有几个键值对的对象数组,我需要根据'updated_at'对它们进行排序:
[
{
"updated_at" : "2012-01-01T06:25:24Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-09T11:25:13Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-05T04:13:24Z",
"foo" : "bar"
}
]
最有效的方法是什么?
使用array .sort()对数组进行排序
克隆数组使用展开运算符(…)使函数纯
按所需键排序(updated_at)
将日期字符串转换为日期对象
Array.sort()的工作原理是,如果current项和next项是一个可以执行无节奏操作的数字/对象,则从current项和next项中减去两个属性
const input = [
{
updated_at: '2012-01-01T06:25:24Z',
foo: 'bar',
},
{
updated_at: '2012-01-09T11:25:13Z',
foo: 'bar',
},
{
updated_at: '2012-01-05T04:13:24Z',
foo: 'bar',
}
];
const sortByUpdatedAt = (items) => [...items].sort((itemA, itemB) => new Date(itemA.updated_at) - new Date(itemB.updated_at));
const output = sortByUpdatedAt(input);
console.log(input);
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' },
{ updated_at: '2012-01-09T11:25:13Z', foo: 'bar' },
{ updated_at: '2012-01-05T04:13:24Z', foo: 'bar' } ]
*/
console.log(output)
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' },
{ updated_at: '2012-01-05T04:13:24Z', foo: 'bar' },
{ updated_at: '2012-01-09T11:25:13Z', foo: 'bar' } ]
*/
为了完整起见,这里有一个sortBy的简短泛型实现:
function sortBy(list, keyFunc) {
return list.sort((a,b) => keyFunc(a) - keyFunc(b));
}
sortBy([{"key": 2}, {"key": 1}], o => o["key"])
注意,这里使用了就地排序的数组排序方法。
对于副本,您可以使用arr.concat()或arr.slice(0)或类似的方法来创建副本。
我已经在Typescript中创建了一个排序函数,我们可以使用它来搜索字符串,日期和对象数组中的数字。它还可以对多个字段进行排序。
export type SortType = 'string' | 'number' | 'date';
export type SortingOrder = 'asc' | 'desc';
export interface SortOptions {
sortByKey: string;
sortType?: SortType;
sortingOrder?: SortingOrder;
}
class CustomSorting {
static sortArrayOfObjects(fields: SortOptions[] = [{sortByKey: 'value', sortType: 'string', sortingOrder: 'desc'}]) {
return (a, b) => fields
.map((field) => {
if (!a[field.sortByKey] || !b[field.sortByKey]) {
return 0;
}
const direction = field.sortingOrder === 'asc' ? 1 : -1;
let firstValue;
let secondValue;
if (field.sortType === 'string') {
firstValue = a[field.sortByKey].toUpperCase();
secondValue = b[field.sortByKey].toUpperCase();
} else if (field.sortType === 'number') {
firstValue = parseInt(a[field.sortByKey], 10);
secondValue = parseInt(b[field.sortByKey], 10);
} else if (field.sortType === 'date') {
firstValue = new Date(a[field.sortByKey]);
secondValue = new Date(b[field.sortByKey]);
}
return firstValue > secondValue ? direction : firstValue < secondValue ? -(direction) : 0;
})
.reduce((pos, neg) => pos ? pos : neg, 0);
}
}
}
用法:
const sortOptions = [{
sortByKey: 'anyKey',
sortType: 'string',
sortingOrder: 'asc',
}];
arrayOfObjects.sort(CustomSorting.sortArrayOfObjects(sortOptions));