Home > Back-end >  how to sum valeus in array when the other values is the same in react js
how to sum valeus in array when the other values is the same in react js

Time:10-31

i have this object

const MyArray = [{name:"vehicle",data:[{y: 500, x: '2022-12-12'},{y: 700, x: '2022-12-12'}]},
{name:"medical",data:[{y: 500, x: '2030-10-12'},{y: 700, x: '2040-12-12'}]}]

and i want this output :

bcs its the same date in the same name

const MyArray = [{name:"vehicle",data:[{y: 1200, x: '2022-10-12'}]},
{name:"medical",data:[{y: 500, x: '2030-10-12'},{y: 700, x: '2040-12-12'}]}]

CodePudding user response:


function addDuplicates(array) {
    const newarr = []
    array.forEach(elem => {
        if (!newarr.some(val => val.x === elem.x)) {
            newarr.push(
                {
                    y: array.filter(value => value.x === elem.x).map(y=>y.y).reduce((p,n)=>p n,0),
                    x: elem.x
                }
            )
        }
    })
    return newarr
}
const output = MyArray.map(elem=>({...elem,data:addDuplicates(elem.data)}))

console.log(output)


i would recommend you if you are using react js then pass the data value in other component and then use the add duplicate function there. It will be simple keeping your components simple and fast processing will be done.

  • Related