Ramda GroupBy - How to group by any prop

Viewed 490

given:

interface Dict {
  [key: string]: any
}

const data: Dict[] = [
  { id: 'a' },
  { id: 'b', b: 'something' },
  { id: 'c', b: 'else' },  
  { id: 'd', extra: 'hello world' },
  { id: 'e' },  
];

where the keys of these Dict objects aren't specified...

How can I get this result?

const result = {
  id: ['a', 'b', 'c', 'd', 'e'],
  b: ['something', 'else'],
  extra: ['hello world'],
  // ... and any other possible key
}
3 Answers

You can flatten the object into a list of pairs, group it, and convert the pairs back to values:

const data = [
  { id: 'a' },
  { id: 'b', b: 'something' },
  { id: 'c', b: 'else' },  
  { id: 'd', extra: 'hello world' },
  { id: 'e' },  
];


let z = R.pipe(
  R.chain(R.toPairs),
  R.groupBy(R.head),
  R.map(R.map(R.last))
)

console.log(z(data))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

Slight variation from Ori Drori answer: (assuming that no properties in your objects are contained in arrays already)

const data = [
  { id: 'a' },
  { id: 'b', b: 'something' },
  { id: 'c', b: 'else' },  
  { id: 'd', extra: 'hello world' },
  { id: 'e' }
];

const run = reduce(useWith(mergeWith(concat), [identity, map(of)]), {});

console.log(
  run(data)
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
<script>const {reduce, useWith, mergeWith, concat, identity, map, of} = R;</script>

Use R.reduce with R.mergeWith and concat all items:

const { mergeWith, reduce } = R

const fn = reduce(mergeWith((a, b) => [].concat(a, b)), {})


const data = [
  { id: 'a' },
  { id: 'b', b: 'something' },
  { id: 'c', b: 'else' },  
  { id: 'd', extra: 'hello world' },
  { id: 'e' },  
];

const result = fn(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

If you need the single value (extra) in array as well, map the items, and wrap with an array, just the values that are not an array already:

const { pipe, mergeWith, reduce, map, unless, is, of } = R

const fn = pipe(
  reduce(mergeWith((a, b) => [].concat(a, b)), {}),
  map(unless(is(Array), of))
)


const data = [
  { id: 'a' },
  { id: 'b', b: 'something' },
  { id: 'c', b: 'else' },  
  { id: 'd', extra: 'hello world' },
  { id: 'e' },
];

const result = fn(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

Related