2
\$\begingroup\$

I am trying to create three buckets of objects. Today, yesterday and past. I am wondering can the following be done in a more concise way in pure JavaScript without any libraries?

const [todayBucket, yesterdayBucket] = [0, 1].map(offset =>
  recordings.filter(({ createdOn }) =>
    moment(createdOn).isSame(moment().add(-offset), 'day'),
  ),
);
const pastBucket = recordings.filter(
  recording => ![...todayBucket, ...yesterdayBucket].includes(recording),
);
\$\endgroup\$
1
\$\begingroup\$

Doing it without an additional library you could try a custom function that does the same thing

function isSame(a,offset) {
    const b = new Date();
    b.setDate(b.getDate() - offset); 
    return a === b
}

const [todayBucket, yesterdayBucket] = [0, 1].map(offset =>
  recordings.filter(({ createdOn }) =>
    isSame(createdOn,offset),
  ),
);
const pastBucket = recordings.filter(
  recording => ![...todayBucket, ...yesterdayBucket].includes(recording),
);
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.