简体   繁体   English

JavaScript 使用自定义布尔值对日期进行排序

[英]JavaScript sort dates with a custom boolean value

I have an array of objects, these objects contains dates and one of them contains an我有一个对象数组,这些对象包含日期,其中一个包含一个

noDate: true

value.价值。 I would like to sort these dates, current I am able to sort them like this:我想对这些日期进行排序,目前我可以像这样对它们进行排序:

data.sort((a, b) => a.date - b.date)

But I need to sort them so the object with the noDate true value becomes the first one in the array.但是我需要对它们进行排序,以便具有 noDate 真值的对象成为数组中的第一个。 I tried this, but it does not work properly:我试过这个,但它不能正常工作:

data.sort((a, b) => a.noDate === true ? -1 : a.date - b.date)

You could take the boolean/ undefined value and take the delta by converting the value to a negated boolean value first.您可以通过先将值转换为否定的布尔值来获取布尔值/ undefined值并获取增量。 Then sort by date .然后按date排序。

 const data = [ { id: 0, noDate: true }, { id: 1, date: new Date('2021-10-30') }, { id: 2, date: new Date('2020-10-30') }, { id: 3, noDate: true }, ]; data.sort((a, b) => !a.noDate - !b.noDate || a.date - b.date); console.log(data); data.sort((a, b) => !b.noDate - !a.noDate || a.date - b.date); console.log(data);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM