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)
CodePudding user response:
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; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>