im looking for a function to add the value of the previous day to each next day.
I have following array:
{x: "8.9.2021", y: 0},
{x: "9.9.2021", y: 33},
{x: "10.9.2021", y: 0},
{x: "11.9.2021", y: 0},
{x: "12.9.2021", y: 0},
{x: "13.9.2021", y: 0},
{x: "14.9.2021", y: 0},
{x: "15.9.2021", y: 8},
{x: "16.9.2021", y: 0},
{x: "17.9.2021", y: 99},
{x: "18.9.2021", y: 0},
{x: "19.9.2021", y: 0},
{x: "20.9.2021", y: 113},
{x: "21.9.2021", y: 57},
{x: "22.9.2021", y: 16},
{x: "23.9.2021", y: 0},
...
And im looking for something like this:
{x: "8.9.2021", y: 0},
{x: "9.9.2021", y: 33},
{x: "10.9.2021", y: 33},
{x: "11.9.2021", y: 33},
{x: "12.9.2021", y: 33},
{x: "13.9.2021", y: 33},
{x: "14.9.2021", y: 33},
{x: "15.9.2021", y: 41},
{x: "16.9.2021", y: 41},
{x: "17.9.2021", y: 140},
{x: "18.9.2021", y: 140},
{x: "19.9.2021", y: 140},
{x: "20.9.2021", y: 253},
{x: "21.9.2021", y: 310},
{x: "22.9.2021", y: 326},
{x: "23.9.2021", y: 326},
...
That is what i tried but that froze my page
const add = (array) => {
let newArray= orders;
for (let i = 0; i < array.length; i ) {
newArray[i] = { x: orders[i].x, y: orders[i].y orders[--i] && orders[--i].y, }; }
return newArray;
};
Didn't find any solutions yet. The solution should be as simple as possible.
CodePudding user response:
You can iterate over the array, and add the values of y
const data = [{x: "8.9.2021", y: 0},
{x: "9.9.2021", y: 33},
{x: "10.9.2021", y: 0},
{x: "11.9.2021", y: 0},
{x: "12.9.2021", y: 0},
{x: "13.9.2021", y: 0},
{x: "14.9.2021", y: 0},
{x: "15.9.2021", y: 8},
{x: "16.9.2021", y: 0},
{x: "17.9.2021", y: 99},
{x: "18.9.2021", y: 0},
{x: "19.9.2021", y: 0},
{x: "20.9.2021", y: 113},
{x: "21.9.2021", y: 57},
{x: "22.9.2021", y: 16},
{x: "23.9.2021", y: 0}]
const incremented = []
data.forEach((el, index) => {
index === 0 ? incremented.push(el) :
incremented.push({...el, y: el.y incremented[index-1].y})
})
console.log(incremented)