美文网首页
将数组按一定的值分组,并将一维数组返回为二维数组

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

作者: 开心就好_635d | 来源:发表于2021-04-15 14:25 被阅读0次

仅作为学习记录下:

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

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

相关文章

网友评论

      本文标题:将数组按一定的值分组,并将一维数组返回为二维数组

      本文链接:https://www.haomeiwen.com/subject/kfbdlltx.html