Chartjs-Is it possible to sum up the properties of an array of objects and to filter it according to another property?

2👍

I’d suggest using Array.reduce() to group dates and visitors by page.

We’d sort the input array to ensure our output is also sorted by date.

The accumulator (acc) will have a property for each page, with a page name, a list of dates and number of visits array.

We’d use Object.values() to get the final array required.

const a = [{ "page": "Page 1", "date": "2021-10-05", "visitors": 10 }, { "page": "Page 2", "date": "2021-10-05", "visitors": 20 }, { "page": "Page 3", "date": "2021-10-05", "visitors": 30 },{ "page": "Page 1", "date": "2021-10-04", "visitors": 40 }, { "page": "Page 2", "date": "2021-10-04", "visitors": 50 }, { "page": "Page 3", "date": "2021-10-04", "visitors": 60 }]

const sortByDate = ({ date: a}, { date:b }) => Date.parse(a) - Date.parse(b);

const result = Object.values(a.sort(sortByDate).reduce((acc, { page, date, visitors}) => { 
    acc[page] = acc[page] || { page, dates: [], numberOfVisits: []};
    acc[page].dates.push(date);
    acc[page].numberOfVisits.push(visitors);
    return acc;
}, {}))

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

You could also structure the output slightly differently, to have a visits array, each element having a date and visitors value.

const a = [{ "page": "Page 1", "date": "2021-10-05", "visitors": 10 }, { "page": "Page 2", "date": "2021-10-05", "visitors": 20 }, { "page": "Page 3", "date": "2021-10-05", "visitors": 30 },{ "page": "Page 1", "date": "2021-10-04", "visitors": 40 }, { "page": "Page 2", "date": "2021-10-04", "visitors": 50 }, { "page": "Page 3", "date": "2021-10-04", "visitors": 60 }]
   
const sortByDate = ({ date: a}, { date:b }) => Date.parse(a) - Date.parse(b);

const result = Object.values(a.sort(sortByDate).reduce((acc, { page, date, visitors}) => { 
    acc[page] = acc[page] || { page, visits: [] };
    acc[page].visits.push( { date, visitors});
    return acc;
}, {}));

console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Leave a comment