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

js group array by value

I’m trying to regroup together values (inside an array) that have the same value

[ [ [ "Mangas", 23809.132685271947 ], [ "Magazines", 2162.858571621124 ], [ "Journal", 0 ], [ "Livres", 2533.654678438289 ] ], [ [ "Mangas", 25809.508799386324 ], [ "Magazines", 2519.527899187236 ], [ "BDs", 0 ], [ "Livres", 2436.7144208655627 ] ] ]

what I want (or something similar to this)

[ 
[ [ "Mangas", 23809.132685271947 ], [ "Mangas", 25809.508799386324 ] ],
[ [ "Magazines", 2162.858571621124 ], [ "Magazines", 2519.527899187236 ] ],
[ [ "Livres", 2533.654678438289 ], [ "Livres", 2436.7144208655627 ] ],
[ [ "Journal", 0 ] ],
[ [ "BDs", 0 ] ]
]

I tried different methods (groupBy, groupByToMap, etc)

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

thanks a lot!!

>Solution :

First, let’s group elements of the same type in an associative array. Then form the answer in the desired form.

var a = [ [ [ "Mangas", 23809.132685271947 ], [ "Magazines", 2162.858571621124 ], [ "Journal", 0 ], [ "Livres", 2533.654678438289 ] ], [ [ "Mangas", 25809.508799386324 ], [ "Magazines", 2519.527899187236 ], [ "BDs", 0 ], [ "Livres", 2436.7144208655627 ] ] ];

let c = {};
for (let a1 of a) {
    for (let a2 of a1) {
        if (c[a2[0]]) {
            c[a2[0]].push(a2);
        } else {
            c[a2[0]] = [a2];
        }
    }
}
let d = [];
for (let c1 in c) {
    d.push(c[c1]);
}
console.log(d);
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