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

How to calculate sum by comparing key value with two object in javascript?

I have below two objects and i need to compare values object with points object based on the given answer like ‘Q1A1’ or ‘Q2A1’ and once key match in both object then it should return the sum of their respective answers.

const values = {
    Q1: {
        Q1A1: "Yes",
    },
    Q2: {
        Q2A1: "Yes",
    },
    Q3: {
        Q3A2: "No",
    },
};

const points = {
    Q1A1: 41,
    Q1A2: 0,
    Q2A1: 19,
    Q2A2: 0,
    Q3A1: 25,
    Q3A2: 0,
};

After comparing both above object based on the given answer the sum will be 60. So, how can i return the sum 60 by comparing these object ?

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

>Solution :

Use the values to drive the script:

const total = Object.values(values)
  .reduce((acc, cur) => acc + Object.entries(cur)
    .reduce((accInner, [key, val]) => val !== 'No' && points[key] ? accInner + points[key] : accInner
    , 0)
  , 0);

console.log(total)
<script>
  const values = {
    Q1: {
      Q1A1: "Yes",
    },
    Q2: {
      Q2A1: "Yes",
    },
    Q3: {
      Q3A2: "No",
    },
  };

  const points = {
    Q1A1: 41,
    Q1A2: 0,
    Q2A1: 19,
    Q2A2: 0,
    Q3A1: 25,
    Q3A2: 5, // should not be counted
  };
</script>

Or (easier to read) make a lookup table and filter+reduce

const lookup = Object.values(values).reduce((acc, cur) => {
  const [key, val] = Object.entries(cur)[0]
  if (val === "Yes") acc[key] = val;
  return acc;
}, {})

console.log(lookup)

const val = Object.entries(points)
  .filter(entry => lookup[entry[0]] && entry[1])
  .reduce((a, b) => a[1] + b[1]);
console.log(val)
<script>
  const values = {
    Q1: {
      Q1A1: "Yes",
    },
    Q2: {
      Q2A1: "Yes",
    },
    Q3: {
      Q3A2: "No",
    },
  };

  const points = {
    Q1A1: 41,
    Q1A2: 0,
    Q2A1: 19,
    Q2A2: 0,
    Q3A1: 25,
    Q3A2: 5, // should not be counted
  };
</script>
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