nested unique flat in javascript

Solution 1:

You could take the upcoming Array#groupBy.

Approach with (own) polyfill.

Array.prototype.groupBy ??= function (callbackfn, thisArg) {
    const O = Object(this);
    const len = O.length >>> 0;
    if (typeof callbackfn !== 'function') throw new TypeError(callbackfn + ' is not a function');

    let k = 0;
    const groups = {};

    while (k < len) {
        const Pk = Number(k).toString();
        const kValue = O[Pk];
        const propertyKey = callbackfn.call(thisArg, kValue, Number(k), O);
        (groups[propertyKey] ??= []).push(kValue);
        ++k;
    }
    return groups;
};


const
    array = [['cb', ''], ['cb', '34'], ['cb', '35'], ['rb', '1']],
    result = Object
        .entries(array
            .filter(([, v]) => v)
            .groupBy(([k]) => k)
        )
        .map(([k, v]) => [k, v.map(([, v]) => v)]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }