Say you have an array of objects like this, which contains a set of date objects:
假设您有一个像这样的对象数组,其中包含一组日期对象 :
const activities = [
{ title: 'Hiking', date: new Date('2019-06-28') },
{ title: 'Shopping', date: new Date('2019-06-10') },
{ title: 'Trekking', date: new Date('2019-06-22') }
]
You want to sort those activities by the date
property.
您想按date
属性对这些活动进行排序。
You can use the sort()
method of Array
, which takes a callback function, which takes as parameters 2 objects contained in the array (which we call a
and b
):
您可以使用Array
的sort()
方法,该方法带有一个回调函数,该函数将数组中包含的2个对象(我们称为a
和b
)作为参数:
const sortedActivities = activities.sort((a, b) => b.date - a.date)
When we return a positive value, the function communicates to sort()
that the object b
takes precedence in sorting over the object a
. Returning a negative value will do the opposite.
当我们返回正值,对功能进行通信sort()
的对象b
优先排序中在对象上a
。 返回负值将执行相反的操作。
The sort()
method returns a new sorted array, but it also sorts the original array in place. Thus, both the sortedActivities
and activities
arrays are now sorted. One option to protect the original array from being modified is to use the slice()
method to create a copy of the array prior to sorting, as follows:
sort()
方法返回一个新的已排序数组,但它也会对原始数组进行适当排序。 因此, sortedActivities
和activities
数组现在都已排序。 保护原始数组免遭修改的一种方法是使用slice()
方法在排序之前创建数组的副本,如下所示:
const sortedActivities = activities.slice().sort((a, b) => b.date - a.date)
翻译自: https://flaviocopes.com/how-to-sort-array-by-date-javascript/