将数组按一定的值分组,并将一维数组返回为二维数组

2021-04-15  本文已影响0人  开心就好_635d

仅作为学习记录下:

//分组,一维数组变为二维数组

function groupBy( array , f ) {

    let groups = {};

    array.forEach(item=>{

        let group = JSON.stringify(f(item));

        groups[group] = groups[group] || []; // groups['John']=groups['Jhone']||[];

        groups[group].push(item);

    });

    console.log('groups:',groups);

    console.log('======================')

    return Object.keys(groups).map(key=> {

        return groups[key];

    });

}

let list = [

    {"name": "John","Average":15,"High":10},

    {"name": "Jane","Average":16,"High":92},

    {"name": "Jane","Average":17,"High":45},

    {"name": "John","Average":18,"High":87},

    {"name": "Jane","Average":15,"High":10},

    {"name": "John","Average":16,"High":87},

    {"name": "John","Average":17,"High":45},

    {"name": "Jane","Average":18,"High":92}

];

let sorted = groupBy(list, (item)=>{

    return [item.name]

});

console.log(sorted);

上一篇下一篇

猜你喜欢

热点阅读