1

I want to create a new object.

An object that adds only values ​​of the same key.

I want to make it in a way that adds num1 to each other and num2 to num2.

The created object has a value of num1 : 4.

But I don't know why the value is NaN

this is my code.


let mydata = [
    {num1: 1 , num2: 2 , num3: 3, num4: 4},
    {num1: 1 , num2: 2 , num3: 3, num4: 4},
    {num1: 1 , num2: 2 , num3: 3, num4: 4},
    {num1: 1 , num2: 2 , num3: 3, num4: 4},
    ]
 
    const sum = {};

  for(let prop of mydata){
    for(let key in prop){
      sum[key] += prop[key];
    }
  }
  
 console.log(sum);
 //{ num1: NaN, num2: NaN, num3: NaN, num4: NaN } => why Nan?? 

2 Answers 2

2

sum[key] default value is undefined, undefined + a number = NaN, so you need to assign 0 for sum[key] initially

let mydata = [{
    num1: 1,
    num2: 2,
    num3: 3,
    num4: 4
  },
  {
    num1: 1,
    num2: 2,
    num3: 3,
    num4: 4
  },
  {
    num1: 1,
    num2: 2,
    num3: 3,
    num4: 4
  },
  {
    num1: 1,
    num2: 2,
    num3: 3,
    num4: 4
  },
]

const sum = {};

for (let prop of mydata) {
  for (let key in prop) {
    if (!sum[key]) {
      sum[key] = 0;
    }
    sum[key] += prop[key];
  }
}

console.log(sum);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

Sign up to request clarification or add additional context in comments.

Comments

2

sum[key] is initially undefined, and undefined + number yields NaN.

You can fix this by assigning a value of zero to sum[key] if its value is falsy:

for(let prop of mydata) {
  for(let key in prop) {
    sum[key] = sum[key] || 0;
    sum[key] += prop[key];
  }
}

Or if you want to condense things further:

for(let prop of mydata) {
  for(let key in prop) {
    sum[key] = (sum[key] || 0) + prop[key];
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.