0

What would be the best way to convert an array of dates into an array of unique objects with a count for each date?

Example Array

['07Sep', '09Sep', '14Sep', '05Sep', '12Sep', '06Sep', '10Sep', '14Sep', '08Sep', '10Sep', '04Sep', '05Sep', '07Sep', '08Sep', '13Sep', '12Sep', '05Sep', '05Sep', '06Sep', '10Sep', '06Sep', '13Sep', '05Sep', '06Sep', '05Sep', '04Sep', '12Sep', '05Sep', '11Sep', '10Sep', '11Sep', '06Sep', '04Sep', '10Sep']

Expected output with this structure: (vales are made up)

[
{04SEP:4},
{06SEP:2},
{07SEP:2},
{09SEP:4},
...
]

2 Answers 2

2

You can do it with a single reduce() statement:

const result = array.reduce((a, v) => ({...a, [v]: (a[v] || 0) + 1}), {});

In each iteration, simply spread the already accumulated result, and then increment the existing value (or 0) for each element.


Snippet:

const array = ['07Sep', '09Sep', '14Sep', '05Sep', '12Sep', '06Sep', '10Sep', '14Sep', '08Sep', '10Sep', '04Sep', '05Sep', '07Sep', '08Sep', '13Sep', '12Sep', '05Sep', '05Sep', '06Sep', '10Sep', '06Sep', '13Sep', '05Sep', '06Sep', '05Sep', '04Sep', '12Sep', '05Sep', '11Sep', '10Sep', '11Sep', '06Sep', '04Sep', '10Sep'];

const result = array.reduce((a, v) => ({...a, [v]: (a[v] || 0) + 1}), {});

console.log(result);

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

2 Comments

Thank you. What would be the best way to also sort these values?
Do you want a single object or an array of single-key objects? Objects are usually considered to be unordered in JavaScript.
1

You can use array#reduce to group the dates and convert to your desired format using Object.entries and array#map.

const input = ['07Sep', '09Sep', '14Sep', '05Sep', '12Sep', '06Sep', '10Sep', '14Sep', '08Sep', '10Sep', '04Sep', '05Sep', '07Sep', '08Sep', '13Sep', '12Sep', '05Sep', '05Sep', '06Sep', '10Sep', '06Sep', '13Sep', '05Sep', '06Sep', '05Sep', '04Sep', '12Sep', '05Sep', '11Sep', '10Sep', '11Sep', '06Sep', '04Sep', '10Sep'],
      result = input.reduce((r, date) => {
        r[date] = (r[date] || 0) + 1;
        return r;
      },{}),
      output = Object.entries(result).map(arr => Object.fromEntries([arr]));
console.log(output);

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.