JS 数组 group by 分组

Posted 烟拢寒水

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS 数组 group by 分组相关的知识,希望对你有一定的参考价值。

扩展数组方法

Array.prototype.groupBy = function groupBy(key)
    const hash = ,
        result = [];
    for (const el of this)
        if (hash[el[key]])
            hash[el[key]].push(el);
        else
            result.push(
                key: el[key],
                values: (hash[el[key]] = [el]),
            );
       
   
    return result;
;

Array.prototype.key = function (key)
    return this.map(el => el[key]);
;

Array.prototype.sum = function (key)
    return this.reduce((total, el) => total + (key ? el[key] : el), 0);
;

Array.prototype.distinct = function ()
    return [...new Set(this)];
;

示例

let arr = [
     name: \'Tom\', sex: \'male\', score: 95 ,
     name: \'Alice\', sex: \'female\', score: 85 ,
     name: \'Bill\', sex: \'male\', score: 58 ,
     name: \'Jack\', sex: \'male\', score: 63 ,
     name: \'Mary\', sex: \'female\', score: 77 ,
];

# 按性别分组计算总分
arr.groupBy(\'sex\').map((key,values)=>(\'sex\':key,\'sum\':values.sum(\'score\')))

# 按性别分组计算人数
arr.groupBy(\'sex\').map((key,values)=>(\'sex\':key,\'sum\':values.length))

 

 

group by JSON包含数组的列

我有下表:

Table

包含这些数据:

Data

如何按我的JSON列中的数组项进行分组?得到这个结果:

Expected Result

答案

您可以尝试使用OPENJSONCROSS APPLY来制作它。

SELECT
    col1,
     UserID
FROM T t1
CROSS APPLY
    OPENJSON(t1.Roles)
    WITH
        (
            col1 varchar(50) N'$'
        ) AS a

sqlfiddle

另一答案

如果你不能使用OPENJSON,这里有一个替代方案

Select
    aRole, COUNT(*) as cnt
From (

    Select
        a.ID
        ,b.Items as aRole
    From 
        (Select *
            ,replace(replace(replace(Roles,'[',''),']',''),'"','') as Rolesx
         From JSONgroup) a
    Cross Apply dbo.Split(a.Rolesx, ',') b
) c
 group by aRole

以上是关于JS 数组 group by 分组的主要内容,如果未能解决你的问题,请参考以下文章