Home > other >  nested unique flat in javascript
nested unique flat in javascript

Time:01-19

Is there some super new ES JavaScript magic that can achieve this ? (I can write a function to achieve this, was just wondering if any new ES202* technique exists )

let arr = [
    ['cb', ''],
    ['cb', '34'],
    ['cb', '35'],
    ['rb', '1']
];

/*
Required Output : 
[['cb', ['34', '35']], ['rb', '1']]
*/

console.log([...new Set(arr.flat(1))])

CodePudding user response:

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

  •  Tags:  
  • Related