Say I have an array of objects:
const peopleArray = [
{
'date': '3/1',
'people': 0
},
{
'date: '3/2',
'people': 5
},
{
'date: '3/3',
'people': 8
},
...
];
I'm trying to draw a chart showing daily difference between the number of people, so I need the following array of objects:
[{
'date': '3/1,
'diff': 0 // Shows 0 the first day.
},
{
'date': '3/2',
'diff': 5 // 5 people joined.
},
{
'date': '3/3',
'diff': 3 // 3 more people joined.
},
...
];
I know I can achieve this with Array.push()
and a for loop:
const peopleArray = [{
date: '3/1',
people: 0
},
{
date: '3/2',
people: 5
},
{
date: '3/3',
people: 8
}
];
let diffArray = [];
for (i = 0; i < peopleArray.length; i++) {
if (i === 0) {
// Shows 0 the first day
diffArray.push({
date: peopleArray[i].date,
diff: 0
});
} else {
diffArray.push({
date: peopleArray[i].date,
diff: peopleArray[i].people - peopleArray[i - 1].people
});
}
}
console.log(diffArray);
But is there a cleaner way to do this with map()
, reduce()
or any of those array functions?