Перебор массива объектов с удалением повторяющейся даты и аккумулированием счетчика
Есть массив объектов :
const dates = [
{date: "2020-08-12", counter: 2},
{date: "2020-08-12", counter: 2},
{date: "2020-08-12", counter: 2},
{date: "2020-08-12", counter: 0},
{date: "2020-08-12", counter: 5},
{date: "2020-08-14", counter: 2},
{date: "2020-08-14", counter: 2},
{date: "2020-08-16", counter: 2},
{date: "2020-08-16", counter: 0},
{date: "2020-08-17", counter: 2},
{date: "2020-08-17", counter: 2},
{date: "2020-08-18", counter: 2},
{date: "2020-08-18", counter: 2},
{date: "2020-08-18", counter: 2},
{date: "2020-08-18", counter: 2},
{date: "2020-08-18", counter: 1},
{date: "2020-08-18", counter: 1},
{date: "2020-08-18", counter: 1},
{date: "2020-08-18", counter: 1},
{date: "2020-08-18", counter: 2}]
В итоге должен получиться массив без повторяющихся дней и просуммированным показателем counter для каждого дня. Например:
newDates = [
{date: '2020-08-12', counter: 11,},
{date: '2020-08-14', counter: 4},
....
]
Пробовал вот так:
uniqueArr = []
for (let i = 1; i <= dates.length; i++) {
if (dates[i].date === dates[i-1].date) {
let date = dates[i-1].date
let uniqCounter = dates[i].counter + dates[i-1].counter
uniqueArr.push({uniqCounter, date})
}
}
Но получается совсем не то, что нужно, даже не понимаю в какую сторону думать.
Ответы (1 шт):
Автор решения: Igor
→ Ссылка
const dates = [
{date: "2020-08-12", counter: 2},
{date: "2020-08-12", counter: 2},
{date: "2020-08-12", counter: 2},
{date: "2020-08-12", counter: 0},
{date: "2020-08-12", counter: 5},
{date: "2020-08-14", counter: 2},
{date: "2020-08-14", counter: 2},
{date: "2020-08-16", counter: 2},
{date: "2020-08-16", counter: 0},
{date: "2020-08-17", counter: 2},
{date: "2020-08-17", counter: 2},
{date: "2020-08-18", counter: 2},
{date: "2020-08-18", counter: 2},
{date: "2020-08-18", counter: 2},
{date: "2020-08-18", counter: 2},
{date: "2020-08-18", counter: 1},
{date: "2020-08-18", counter: 1},
{date: "2020-08-18", counter: 1},
{date: "2020-08-18", counter: 1},
{date: "2020-08-18", counter: 2}
];
let newDates = [];
let lookup = {};
dates.forEach(i => lookup[i.date] = (lookup[i.date] || 0) + i.counter);
Object.keys(lookup).forEach(i => newDates.push({date: i, counter: lookup[i]}));
console.log(newDates);