Search code examples
javascriptarraysgrouping

Grouping arrays into further sub arrays


Say I have an array of arrays like so:

const input = [[1, 'aaa'], [1, 'bbb'], [2, 'ccc'], [2, 'ddd']]

I would like to arrange it so that they are futher sorted into groups of arrays, with the first element in each dictating how they are sorted. The result would look like this:

const output = [[[1, 'aaa'], [1, 'bbb']], [[2, 'ccc'], [2, 'ddd']]]

The first group would have all arrays where the first element is 1, the second group would all have 2 as the first element, and so forth.

The second solution to this question is probably the closest thing I can find: Grouping array group into separate sub array group

However, my modifications don't seem to work and I imagine I am misunderstand something about the functionality of .reduce(). What I've tried:

const input = [[1, 'aaa'], [1, 'bbb'], [2, 'ccc'], [2, 'ddd']];

const output = input.reduce(
  (r, c, i, a) => (
    c[0] != a[i - 1][0] ? r.push([c]) : r[r.length - 1].push(c), r
  ), []);

Am I heading in the right direction, or is there a more simple solution that lies elsewhere?


Solution

  • So basically what i'm doing here (inside the .reduce()) is searching for a group that contains a value ([number, string]) which number (id) is equal to the number of the value i'm trying to add. If i find a group i push the new value (nv) inside that group, else i create a new group ([nv])

    const input = [[1, 'aaa'], [1, 'bbb'], [2, 'ccc'], [2, 'ddd'], [4, 'aaa'], [5, 'aaa']]
    
    const output = input.reduce((groups, nv) => {
        const group = groups.find(g => g.some(([id]) => id === nv[0]))
        
        if(!group) groups.push([nv])
        else group.push(nv)
    
        return groups
    }, [])
    
    // output: [[[1, 'aaa'], [1, 'bbb']], [[2, 'ccc'], [2, 'ddd']], [[4, 'aaa']], [[5, 'aaa']]]