Javascript - 分层抽样

时间:2015-04-04 04:21:47

标签: javascript json underscore.js lodash

我有一个像这样的json数据源:

var ds=[{"id":1,"group":"A"},{"id":2,"group":"C"},{"id":3,"group":"B"},{"id":4,"group":"A"},{"id":5,"group":"C"},{"id":6,"group":"B"},{"id":7,"group":"A"},{"id":8,"group":"C"},{"id":9,"group":"B"},{"id":10,"group":"A"},{"id":11,"group":"C"}];

假设每个组至少有m个记录(此处m = 3),我想从每个组中随机选择n(n <= m)个记录并将样本合并到一个新的数组中,如下所示:

var output=[{"id":1,"group":"A"},{"id":7,"group":"A"},{"id":3,"group":"B"},{"id":6,"group":"B"},{id":2,"group":"C",{"id":11,"group":"C"}]

与此案例有关的任何算法?

1 个答案:

答案 0 :(得分:1)

是的,你可以用lodash干净利落地做到这一点:

var output = _(ds) //begin chaining syntax
    .groupBy("group") //split into groups
    .map(function(group) { //for each group
        return _.sample(group, n); //sample n items randomly
    })
    .flatten() //flatten array of arrays into a single array
    .value(); //end chaining syntax