JavaScript SUM and GROUP BY of JSON data

后端 未结 5 1182
广开言路
广开言路 2020-12-02 13:46

This is my first attempt at doing JavaScript with some JSON data objects and need some advice on the proper way to attain my goal.

Some server-side code actually gen

5条回答
  •  春和景丽
    2020-12-02 14:17

    Hi here is one solution written by me Visit: aggregate_groupby_js on npm or in aggregate_groupby_js on github

    The javascript library for using aggregate functions on array of objects. Basic functions like SUM, MIN, MAX, AVG, DISTINCT_COUNT for entire javascript objects

    Example:

    var arr = [{`"shape"`:`"square"`,`"color"`:`"red"`,`"used"`:1,`"instances"`:1},
        {`"shape"`:`"square"`,`"color"`:`"red"`,`"used"`:2,`"instances"`:1},
        {`"shape"`:`"circle"`,`"color"`:`"blue"`,`"used"`:0,`"instances"`:0},
        {`"shape"`:`"square"`,`"color"`:`"blue"`,`"used"`:4,`"instances"`:4},
        {`"shape"`:`"circle"`,`"color"`:`"red"`,"`used"`:1,`"instances"`:1},
        {`"shape"`:`"circle"`,`"color"`:`"red"`,`"used"`:1,`"instances"`:0},
        {`"shape"`:`"square"`,`"color"`:`"blue"`,`"used"`:4,`"instances"`:5}, 
        {`"shape"`:`"square"`,`"color"`:`"red"`,`"used"`:2,`"instances"`:1}];
    
    // Specify columns
        var columns =[`"used"`, `"instances"`];
    
    // Initialize object
        var gb = new GroupBy(arr,columns);
    // or
        var gb = new GroupBy(arr,[`"used"`, `"instances"`]);
    
    // Call the aggregate functions    
        gb.sum();
        gb.min();
        gb.max();
        gb.avg();
        gb.distinctCount();
    

提交回复
热议问题