0

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)

thanks a lot!!

  • 1
    Could you show us the implementations of what you've tried? – Emiel Zuurbier Apr 09 '23 at 16:07
  • It does not look like a pleasant structure to deal with. It is certainly possible, but you say that you're ok with something similar. Would an object like this fit well ? `{ mangas: [23809.132685271947, 25809.508799386324], magazines: [2162.858571621124, 2519.527899187236] }`. Also, maybe you could find answers here https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects – AlanOnym Apr 09 '23 at 16:19
  • Have a look at [.flat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) – Louys Patrice Bessette Apr 09 '23 at 16:20

1 Answers1

0

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);
Alexey Obukhov
  • 834
  • 9
  • 18