如何在JavaScript中按日期值对数组进行排序

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):

您可以使用Arraysort()方法,该方法带有一个回调函数,该函数将数组中包含的2个对象(我们称为ab )作为参数:

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()方法返回一个新的已排序数组,但它也会对原始数组进行适当排序。 因此, sortedActivitiesactivities数组现在都已排序。 保护原始数组免遭修改的一种方法是使用slice()方法在排序之前创建数组的副本,如下所示:

const sortedActivities = activities.slice().sort((a, b) => b.date - a.date)

翻译自: https://flaviocopes.com/how-to-sort-array-by-date-javascript/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值