Estoy buscando una función para agregar el valor del día anterior a cada día siguiente.
Tengo la siguiente matriz:
{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}, ...Y estoy buscando algo como esto:
{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}, ...Eso es lo que intenté pero eso congeló mi página.
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; };No encontró ninguna solución todavía. La solución debe ser lo más simple posible.
Puede iterar sobre la matriz y agregar los valores de 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)