Sylar
Sylar

Reputation: 12092

Underscore.js groupBy two levels

I can't seem to word this properly by I need to group by date and foo:

// Using date as numbers for clear example
// date key should be grouped into a key
// Under that key (date), I should see another key of "foo"

let list = [
  { date: "1", foo: "me", result: "meFoo"},
  { date: "1", foo: "me2", result: "meYou"},
  { date: "1", foo: "me3", result: "meHe"},
  { date: "2", foo: "me", result: "meHim"},
  { date: "2", foo: "me2", result: "meHim"}
]

let grouped = _.groupBy(list, "date") // keys ie 1, 2

// I need another key under the date key, possible?
let grouped = _.groupBy(list, "date", (val) => _.groupBy(val), "foo") // result not expected

I'm getting a bit complex here so I used underscore to ease the complexity. Is this possible?

I'll then do something like, I could use _.pluck:

Object.keys(grouped).map( dateKey => Object.keys(grouped[dateKey]).map(fooKey => console.log( grouped[dateKey][fookey][0] )) )

That really looks wrong on the highest level.

Expected results to look something like:

DATE // key
 |
 |___ FOO // key
       |
       |__ array foo objects

Upvotes: 0

Views: 1987

Answers (4)

demux
demux

Reputation: 4654

Functional (using reduce):

list.reduce((acc, item) => {
  const key1 = item.date
  const group1 = acc[key1] || {}
  const key2 = item.foo
  const group2 = group1[key2] || []
  return {
    ...acc,
    [key1]: {
      ...group1,
      [key2]: group2.concat(item)
    }
  }
}, {})

Procedural:

let grouped = {}

list.forEach((item) => {
    // Create an empty object if this key has not already been set:
    grouped[item.date] = grouped[item.date] || {}

    // Create an empty list if this key has not already been set:
    grouped[item.date][item.foo] = grouped[item.date][item.foo] || []

    // Push the item to our group:
    grouped[item.date][item.foo].push(item)
})
In python this would be:
from collections import defaultdict

_list = [
    {"date":"1","foo":"me","result":"meFoo"},
    {"date":"1","foo":"me2","result":"meYou"},
    {"date":"1","foo":"me3","result":"meHe"},
    {"date":"2","foo":"me","result":"meHim"},
    {"date":"2","foo":"me2","result":"meHim"}
]

grouped = defaultdict(lambda: defaultdict(list))

for item in _list:
    grouped[item['date']][item['foo']].append(item)

Upvotes: 5

Gruff Bunny
Gruff Bunny

Reputation: 27986

You were nearly there. For the second level of grouping you need to map across the values of the first grouping:

let result = _.chain(list)
    .groupBy('date')
    .mapObject( grp => _.groupBy(grp, 'foo'))
    .value();

Upvotes: 1

Ajay Gaur
Ajay Gaur

Reputation: 5280

This will give you the desired array.

_.map(_.groupBy(list, 'date'), (value, key) => ({[key]: _.groupBy(value, 'foo')}))

I hope you want such result:

var list = [{ date: "1", foo: "me", result: "meFoo" }, { date: "1", foo: "me2", result: "meYou" }, { date: "1", foo: "me3", result: "meHe" }, { date: "2", foo: "me", result: "meHim" }, { date: "2", foo: "me2", result: "meHim" }],
    grouped = _.map(_.groupBy(list, 'date'), (value, key) => ({[key]: _.groupBy(value, 'foo')}));

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Upvotes: 2

Vipin Kumar
Vipin Kumar

Reputation: 6546

Here is another way to achieve this using function composition. I have used Ramda library for this. First, group it via date and then group it via foo. Also, please note that I didn't find any curried function for iterating object keys, that is why I added it myself.

let list = [
  { date: "1", foo: "me", result: "meFoo"},
  { date: "1", foo: "me2", result: "meYou"},
  { date: "1", foo: "me3", result: "meHe"},
  { date: "2", foo: "me", result: "meHim"},
  { date: "2", foo: "me2", result: "meHim"},
  { date: "2", foo: "me2", result: "meHimAnother"}
]

function iterKeys(fn) {
  return function(obj) {
    for (var key in obj) {
      obj[key] = fn(obj[key])
    }
    return obj;
  }
}

var group = R.compose(iterKeys(R.groupBy(R.prop('foo'))), R.groupBy(R.prop('date')))
console.log(group(list));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

Upvotes: 0

Related Questions