0

I'm trying to sum the values inside an array depending on which levels they are but with no success for the moment.

Datas I'm working with ( named as the variable totalByLevel ) :

enter image description here

What I want :

Having each total per level inside 1 array, for example : ['total of 3 + 4', 'total of 6 + 7', etc...]

What I tried :

I tried to create an empty array and push the values from 3 + 4 into the array, which is working but not as intented.

enter image description here

Only the last values is kept in the array and all others are erased, if you have a fix for it I would really appreciate any help! Thank you in advance.

component.ts

for (const levelKey in this.totalByLevel ) {
        if (this.totalByLevel .hasOwnProperty(levelKey)) {
          const key = this.labelName[levelKey];
          const value = this.totalByLevel [levelKey][Object.keys(this.totalByLevel [levelKey])[0]];
          const value2 = this.labelName[Object.keys(this.totalByLevel [levelKey])[0]];
          const value3 = this.totalByLevel [levelKey][Object.keys(this.totalByLevel [levelKey])[1]];
          const value4 = this.totalByLevel [levelKey][Object.keys(this.totalByLevel [levelKey])[2]];

          this.output_object[key] = value;
          this.output_object2[key] =  value2;
          const sum = [];
          if (value4 !== undefined || null) {
            sum.push((+value + +value3 + +value4).toFixed(2));
            console.log(sum, 'SUM 3');
            this.totalPerCat = sum;

          } else if (value4 === undefined || null) {
             sum.push((+value + +value3).toFixed(2));
             console.log(sum, 'SUM 2');
             this.totalPerCat = sum;

          } else if (value3 === undefined || null) {
            sum.push(value);
            console.log(sum, 'SUM 1');
            this.totalPerCat = sum;

          }
          console.log(this.totalPerCat);
/*          console.log(value3);
          console.log(value4);
          console.log(+value + +value3 + +value4, 'SUM');*/
        }
      }
    });
4
  • 1
    You should probably read about truthy and falsy values in JS: developer.mozilla.org/en-US/docs/Glossary/Truthy (Not answering the question but this could greatly improved your if...else management) Commented Sep 7, 2020 at 7:48
  • @Zer0 so if I understand right, what I was doing wrong there is that I was overwriting the value inside the array each time my else if was triggered, am I right ? Commented Sep 7, 2020 at 8:15
  • 1
    First this and your if/else conditions are just not well put, for example value4 !== undefined || null: I assume you meant value4 !== undefined || value4 !== null? The code you wrote would just convert the null to false (due to falsy values), making it useless and only checking for undefined. But you could even take it further: value4 !== undefined || null => if (value4) value4 === undefined || null => if (!value4)`. That's the magic of truthy/falsy in JS ;) Commented Sep 7, 2020 at 8:29
  • Thank you a lot for the very good explication. I will for sure keep that in mind! Commented Sep 7, 2020 at 8:32

2 Answers 2

1

Here you go:

const data={
    2:{3:"3514.80", 4:"7259.32"},
    5:{6:"864941.86", 7:"1076976.54"},
    8:{"":"14145.69"},
    9:{10:"223835.02", 11:"60978.31", 12:"5554.92"}
}

const result = Object.values(data).map(items => Object.values(items).map(val => Number(val)).reduce((a,b) => a + b, 0))

console.log(result)

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

Comments

1

You could use the funcitons Object.values() and Array reduce in combination. Try the following

var totalByLevel = {
  2: {
    3: '3514.80',
    4: '7259.32'
  },
  5: {
    6: '864941.86',
    7: '1076976.54'
  }
};

var sum = Object.values(totalByLevel).reduce((acc, curr) => {
  acc.push(String(Object.values(curr).reduce((a, c) => a + Number(c), 0)));
  return acc;
}, []);

console.log(sum);

3 Comments

I'm getting the following : error TS2339: Property 'push' does not exist on type 'unknown'.
@Zephyr: Did you give the seed value [] at the end of the first reduce?
Oh right! My bad sorry I rushed into it and actually didn't, works as well now!

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.