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 group array element to a new group array?

I have an array of lines:

   this.lines = [
    0: {indexLine: 0, group: 16, columns: [,…]}
    1: {indexLine: 1, group: 16,…}
    2: {indexLine: 2, group: 16,…}
    3: {indexLine: 3, group: 9,…}
    ]

I want to group lines by group to be able render it in different tables.

I have tried this:

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

 let arr: any = {};
        this.lines.forEach((line) => {
          if (!arr[line.group]) {
            arr[line.group] = [];
          }

          arr[line.group].push(line);
        });

>Solution :

You can use Set to get unique group values from array of object. new Set(lines.map(x => x.group) will give you array of unique values of group.

Convert that set to array with Array.from().

Now you can use map to iterate through unique group values and Array.filter would give you all matching elements.


let lines = [
    {indexLine: 0, group: 16},
    {indexLine: 1, group: 16},
    {indexLine: 2, group: 16},
    {indexLine: 3, group: 9},
];

const groupedLines = Array.from(new Set(lines.map(x=>x.group))).map(y => lines.filter(z => z.group === y));

console.log(groupedLines);
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