Home > Mobile >  How to group together same elements into a new Array
How to group together same elements into a new Array

Time:11-13

Below is an array containing some elements:

const arr = ['a', 'b', 'c', 'a', 'b', 'c', 'd']

So how can I create a new array where same elements are grouped together into a new array like this:

const arr = [['a','a'], ['b','b'], ['c','c'], ['d']]

Thank you for your time.

CodePudding user response:

This can be achieved with the most generic of group by operations.

const arr = ['a', 'b', 'c', 'a', 'b', 'c', 'd'];

const grouped = Object.values(arr.reduce((a, n) => ((a[n] ??= []).push(n), a), {}));

console.log(grouped);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

This is one way to do it. More explicit, but easier to understand and translate to other languages as well. Time: O(n), Space: O(n), n is number of elements in array

function process(arr) {
    const map = arr.reduce((acc, e) => {
        if (!acc.has(e)) {
            acc.set(e, 0);
        }
        acc.set(e, acc.get(e)   1);
        return acc;
    }, new Map())

    const res = [];
    for (const[k, v] of map.entries()) {
        const localRes = [];
        for (let i = 1; i <= v; i  ) {
            localRes.push(k);
        }
        res.push(localRes);
    }
    return res;
}

const arr = ['a', 'b', 'c', 'a', 'b', 'c', 'd']
console.log(process(arr));

Result:

[ [ 'a', 'a' ], [ 'b', 'b' ], [ 'c', 'c' ], [ 'd' ] ]
  • Related