使用lodash / underscore进行聚合排序限制

时间:2015-12-03 07:01:34

标签: javascript mongodb sorting underscore.js lodash

我需要汇总我的数据。如果我使用mongodb聚合,这将很容易,但我想在客户端执行。 LoDash或Underscore应该解决这个问题......

假设我有这些数据:

var data = [
    {
        "uId" : "u1",
        "qId" : "q1",
        "share" : 2,
        "star"  :   2,
        "score" : 5
    },
    {
        "uId" : "u1",
        "qId" : "q2",
        "share" : 2,
        "star"  :   2,
        "score" : 5
    }.
    {
        "uId" : "u2",
        "qId" : "q1",
        "share" : 2,
        "star"  :   2,
        "score" : 5
    },
    {
        "uId" : "u2",
        "qId" : "q2",
        "share" : 3,
        "star"  :   3,
        "score" : 7
    },
    {
        "uId" : "u3",
        "qId" : "q1",
        "share" : 3,
        "star"  :   3,
        "score" : 7
    },
    {
        "uId" : "u3",
        "qId" : "q2",
        "share" : 3,
        "star"  :   3,
        "score" : 7
    }
]

我需要这个结果:

result = [
    {
        "uId" : "u3",
        "qId" : 2,
        "share" : 6,
        "star"  :   6,
        "score" : 14
    },
    {
        "uId" : "u2",
        "qId" : 2,
        "share" : 5,
        "star"  :   5,
        "score" : 12
    }
]

按最高分数排序,并将结果限制为仅显示2个结果

谢谢你......

2 个答案:

答案 0 :(得分:3)

您也可以在下划线中执行此操作。

_.sortBy(data, 'score').reverse().splice(0, 2);

不确定反向的表现如何。

编辑:

没有反过来得到它:

_.sortBy(data, function (el) { return -el.score; }).splice(0, 2);

答案 1 :(得分:0)

你可以使用lodash:

declare @NumberOfQuestions int

set @NumberOfQuestions = (
    select count(*) 
    from question_master
    )

declare @sql varchar(max)

set @sql = 'select om1.opt '

declare @counter int

set @counter = 2
while @Counter <=  @NumberOfQuestions
begin
    set @sql = @sql + '
    , om' + cast (@counter as varchar(1)) + '.opt '
    set @counter = @counter + 1
end

set @sql = @sql + '
    from option_master om1 '

set @counter = 2
while @Counter <=  @NumberOfQuestions
begin
    set @sql = @sql + '
    cross join option_master om' + cast(@counter as varchar(1)) + ' '
    set @counter = @counter + 1
end

set @sql = @sql + '
    order by om1.opt '

set @counter = 2
while @Counter <=  @NumberOfQuestions
begin
    set @sql = @sql + '
    , om' + cast(@counter as varchar(1)) + '.opt '
    set @counter = @counter + 1
end

exec (@sql)

首先,它将创建一个排序数组,然后将结果限制为只有两个结果。