1

I have the following javascript array:

[{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:-1, Feb:0.34 }]

I would like to add the total of Jan and Feb as a new property in the existing array.

Example:

[{ Year:2000, Jan:1, Feb:, Total: 1 }, {Year:2001, Jan:2, Feb:4, Total: -0.66 }]

How can I do this using JavaScript?

EDIT: Updated with decimal values

developer
  • 1,401
  • 4
  • 28
  • 73

3 Answers3

4

Assuming the empty value in Feb means 0 the following code will work.

var data = [{ Year:2000, Jan:1, Feb:0 }, {Year:2001, Jan:2, Feb:4 }];

data.forEach(item => {
    item.Total = item.Jan + item.Feb;
});


console.log(data); /* [
  { Year: 2000, Jan: 1, Feb: 0, Total: 1 },
  { Year: 2001, Jan: 2, Feb: 4, Total: 6 }
]*/


Josh Hales
  • 394
  • 2
  • 12
  • 1
    Thank you, I have updated the question with decimal values. Somehow I get -0.65999999 instead of -0.66 for Year 2001. Any idea? – developer Feb 23 '21 at 12:45
  • That is what is known as a floating-point error. It is to do with how computers store the value of non-integer numbers. [This](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) thread should help with that as it is a different issue to your question. – Josh Hales Feb 23 '21 at 12:58
1

Given:

const myArray = [{ Year:2000, Jan:1, Feb: 2}, {Year:2001, Jan:2, Feb:4 }];

Just iterate over the months.

myArray.forEach(y => y.Total = y.Jan + y.Feb)

You can add more months to it

myArray.forEach(y => y.Total = y.Jan + y.Feb + y.Mar + y.Apr)
entio
  • 3,816
  • 1
  • 24
  • 39
1

Suppose data to have the array.

const data = [{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:2, Feb:4 }]

You can use Array.forEach to change the existing array.

data.forEach((item) => {
    const total = (item.Jan || 0) + (item.Feb || 0);
    item.Total = total;
});

here (item.Jan || 0) would ensure 0 for an undefined Jan

Shrey Gupta
  • 392
  • 4
  • 10