2

I have an array of objects like:

const dates = [
  {date: "Jul 06 2018", count: 10},
  {date: "Jul 08 2018", count: 1},
  {date: "Jul 10 2018", count: 120},
];

I am working with the eachDay and format functions of date-fns to generate and "backfill" all dates that exist between the first and last dates for the given array.

eachDay(
  dates[0].date,
  dates.slice(-1)[0].date,
)
  .map(d => ({
    x: d.dateCollected,
    y: dates
      .filter(e => d.dateCollected === format(e, 'MMM DD YYYY')),
  }));

That codes returns all the dates, but I cannot get the count value from the original array into the "backfilled" array.

The expected outcome:

const result =  = [
  {x: "Jul 06 2018", y: 10},
  {x: "Jul 07 2018", y: 0},
  {x: "Jul 08 2018", y: 1},
  {x: "Jul 09 2018", y: 0},
  {x: "Jul 10 2018", y: 120},
];
2
  • Why do define x and y properties in your code when the expected outcome should not have those properties? What is the idea? Commented Dec 18, 2018 at 23:52
  • Updated - I inadvertently copy/pasted from the first object. The expected outcome would be with x and y keys. Commented Dec 18, 2018 at 23:55

2 Answers 2

2

You can simplify things by creating a lookup of count by date:

const {eachDay, format} = dateFns;

const dates = [
  {date: "Jul 06 2018", count: 10},
  {date: "Jul 08 2018", count: 1},
  {date: "Jul 10 2018", count: 120}
];

const counts = dates.reduce((memo, {date, count}) => {
  memo[date] = count;
  return memo;
}, {});

const result = eachDay(
  dates[0].date,
  dates.slice(-1)[0].date
)
  .map(d => {
    const x = format(d, "MMM DD YYYY");
    return {x, y: counts[x] || 0};
  })

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

2

According to the documentation for eachDay the function returns string values, not objects with a dateCollected property.

You could produce the desired result it like this:

const {eachDay, format} = dateFns; // Just needed for this snippet to run

const dates = [
  {date: "Jul 06 2018", count: 10},
  {date: "Jul 08 2018", count: 1},
  {date: "Jul 10 2018", count: 120},
];

const result = eachDay(
  dates[0].date,
  dates.slice(-1)[0].date,
).map(x => format(x, "MMM DD YYYY"))
.map(x => ({ x, y: (dates.find(d => d.date === x) || { count: 0 }).count }));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.