skip to Main Content

I’m having a bit of an issue figuring this out.

I have an array object per customer, per year of the month:

[
  {
    color: "#009192",
    data: [0, 0, 57.62, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client 1"
  },
  {
    color: "#009192",
    data: [0, 0, 234.65, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client 2"
  },
  {
    color: "#009192"
    data: [0, 0, 490.43, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    label: "Client 3"
  },
  {
    color: "#009192"
    data: [0, 0, 0, 94.00, 0, 0, 0, 0, 0, 0, 0, 0]
    label: "Client 1"
  }
]

How do I add the two objects with the same label (Client 1) and create a new array that would look like this?

[
  {
    color: "#009192",
    data: [0, 0, 57.62, 94.00, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client 1"
  },
  {
    color: "#009192",
    data: [0, 0, 234.65, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client 2"
  },
  {
    color: "#009192"
    data: [0, 0, 490.43, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    label: "Client 3"
  },
]

Thank you!

2

Answers


  1. You can use Array#reduce with an object to store the values for each label and sum the data array for objects with the same same label.

    let arr=[{color:"#009192",data:[0,0,57.62,0,0,0,0,0,0,0,0,0],label:"Client 1"},{color:"#009192",data:[0,0,234.65,0,0,0,0,0,0,0,0,0],label:"Client 2"},{color:"#009192",data:[0,0,490.43,0,0,0,0,0,0,0,0,0],label:"Client 3"},{color:"#009192",data:[0,0,0,94,0,0,0,0,0,0,0,0],label:"Client 1"}];
    let res = Object.values(arr.reduce((acc, {color,data,label}) => {
      if (acc[label]) acc[label].data.forEach((x, i, a) => a[i] += data[i]);
      else acc[label] = {color, data, label};
      return acc;
    }, {}));
    console.log(JSON.stringify(res));
    Login or Signup to reply.
  2. Hope this can help you

    one = [
      {
        color: "#009192",
        data: [0, 0, 57.62, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        label: "Client 1"
      },
      {
        color: "#009192",
        data: [0, 0, 234.65, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        label: "Client 2"
      },
      {
        color: "#009192",
        data: [0, 0, 490.43, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        label: "Client 3"
      },
      {
        color: "#009192",
        data: [0, 0, 0, 94.00, 0, 0, 0, 0, 0, 0, 0, 0],
        label: "Client 1"
      }
    ];
    
    console.log(one)
    
    let two = one.reduce((acc, cur) => {
        //console.log(acc);
    
        let index = (!acc.length ? null : acc.findIndex((item) => item.label === cur.label));
    
        if (index !== null && index >= 0) {
            acc[index].data = acc[index].data.map((value, i) => acc[index].data[i] += cur.data[i]);
        } else {
            acc.push(cur)
        }
        
        return acc;
    }, []);
    
    console.log(two);
    

    Regards

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search