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!!

3
  • 1
    Could you show us the implementations of what you've tried? Commented Apr 9, 2023 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 stackoverflow.com/questions/14446511/… Commented Apr 9, 2023 at 16:19
  • Have a look at .flat() Commented Apr 9, 2023 at 16:20

1 Answer 1

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);

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

1 Comment

Please don't write answers containing only code and links. Prrovide an explanation of what your code does and why it works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.