按日期排序对象数组 [英] Order array of objects by date
问题描述
例如
myArr= [
{name:"Joe", id:3, date: "2012.10.12"},
{name:"Ed", id:43, date: "2012.02.12"},
{name:"Mark", id:22, date: "2012.02.11"}
];
那么如何按日期对这个数组进行排序?
so how can I sort this Array by date?
这只是一个小例子,但它就像是 Array 中的 1000 个对象.我在 Internet 上搜索并找到了一些使用 sort()
函数的示例,但它在我的大数组中不起作用.
This is just small example, but it will be like 1000 Objects inside that Array.
I have searched on the Internet and found some examples that used the sort()
function but it doesn't work in my big Array.
推荐答案
假设日期只是按照您的代码格式化的字符串,您可以这样做:
Assuming the dates are just strings formatted as in your code, you can do this:
myArr.sort( (a,b) => a.date.localeCompare(b.date) )
sort
方法将一个函数作为参数,每次需要比较数组的两个元素时都会调用该函数.因此,要按特定字段排序,您需要传递一个函数来比较传入的两个对象的这些字段.
The sort
method takes as a parameter a function that will be called every time it needs to compare two elements of the array. So to sort by a particular field, you pass a function that compares those fields of the two objects passed in.
排序比较器函数必须返回一个表示正确顺序的特殊值:-1 如果第一个参数(通常称为 a
)应该在第二个(b
);1 如果 b
应该在 a
之前;或 0 如果它们相等(所以顺序无关紧要).幸运的是,已经有一个方法可以比较字符串并为 sort
返回正确的值(如果你在 a
上调用它并将 b
作为参数传递): localeCompare
.由于您要比较的字段是字符串,因此您只需在比较函数中的字段上调用它即可返回正确的排序值.
The sort comparator function has to return a special value indicating the correct order: -1 if the first parameter (conventionally called a
) should come before the second (b
); 1 if b
should come before a
; or 0 if they're equal (so the order doesn't matter). Fortunately, there's already a method that compares strings and returns the proper value for sort
(if you call it on a
and pass b
as a parameter): localeCompare
. Since the fields you're comparing are strings, you can just call that on the fields in your comparison function to return the proper value for the sort.
这篇关于按日期排序对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!