简体   繁体   中英

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. 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. Then sort by 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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