I have a json data source like this:
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"}];
Suppose that every group has at least m records(here m=3),I would like to randomly pick n(n<=m) records from each group and merge the samples into a new array like this:
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"}]
Any algorithm to do with this case?
Yeah, you can do this pretty cleanly with 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With