Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sum of same keys of an array objects to produce new object

I have an array object:

const data = [
  { label: 'P', value: 13 },
  { label: 'P', value: 7 },
  { label: 'Q', value: 15 },
  { label: 'Q', value: 8 },
  { label: 'Q', value: 1 },
  { label: 'R', value: 5 },
  { label: 'S', value: 6 }
]

I need to produce an object which keeps the sum of the value for each key. So,the output will be:

{P: 20, Q: 24, R: 5, S: 6}

I am struggling to generate the output.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const data = [
  { label: 'P', value: 13 },
  { label: 'P', value: 7 },
  { label: 'Q', value: 15 },
  { label: 'Q', value: 8 },
  { label: 'Q', value: 1 },
  { label: 'R', value: 5 },
  { label: 'S', value: 6 }
]

const customData = data.reduce((acc, cur) => {
    let common = acc.length > 0 && acc.filter(item => item.label === cur.label)
    if (common) {
        common.value += cur.value
    } else {
        
    }
    return acc
}, {})

console.log(customData)
// expected output {P: 20, Q: 24, R: 5, S: 6}

>Solution :

Check to see if the key exists. If it doesn’t set it to zero, and add the value to it. Otherwise add the value.

const data = [
  { label: 'P', value: 13 },
  { label: 'P', value: 7 },
  { label: 'Q', value: 15 },
  { label: 'Q', value: 8 },
  { label: 'Q', value: 1 },
  { label: 'R', value: 5 },
  { label: 'S', value: 6 }
]

const customData = data.reduce((acc, cur) => {

    // Destructure the label and value from the object
    const { label, value } = cur;

    // If the label isn't present as a key on
    // the accumulator, set its value to zero, and then
    // add the value from the current object,
    // otherwise just add the value.
    acc[label] = (acc[label] || 0) + value;

    return acc;

}, {})

console.log(customData);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading