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

Group values inside a loop and return it as an object with typescript

New to typescript so not sure how to map values inside a loop. I am running a function which does some logic which returns a number(nothing special). This function will be called in a other function to return 2 values, 1. is a number 2. is a string.

export class matrix {

     public pattern!: {[key: string]: number[]};

     // function will be called in a loop in a different function
     public setPattern(data: number, category: string): void {

         // does some logic here and set row as a value
         const row = 10;// random value of course
 
         this.pattern[category].push(row);// not working of course
     
     } 
}
     
//output should be like this  
{
    "some category": [10,55,4,53,1],
    "more rows": [1,2,8]
} 

>Solution :

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

Probably not working when array is not initialized

Add this before pushing new element

if(this.pattern[category] == undefined) this.pattern[category] = []

And then after array is initialized push new element to it

this.pattern[category].push(row);

Also make sure that pattern object is initialized

public pattern!: {[key: string]: number[]}; = {}
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