3

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?

ken wang
  • 165
  • 1
  • 12
  • 1
    something like http://stackoverflow.com/questions/20292750/unique-random-values-from-array-of-unique-values-javascript – mplungjan Apr 04 '15 at 04:30

1 Answers1

3

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
Adam Boduch
  • 11,023
  • 3
  • 30
  • 38
Retsam
  • 30,909
  • 11
  • 68
  • 90