2015-04-04 69 views
1

我有一個這樣的JSON數據源:使用Javascript - 分層抽樣

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 < =米)從每個組記錄,並將樣品合併成一個新的數組這樣的:

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

像http://stackoverflow.com/questions/20292750/unique-random-values-from-array-of-unique-values -javascript – mplungjan 2015-04-04 04:30:05

回答

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 
+0

偉大的工作!謝謝。 – 2015-04-04 05:25:48