Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ramda GroupBy - How to group by any prop

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
}
like image 963
Hitmands Avatar asked Dec 31 '22 21:12

Hitmands


1 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>
like image 144
georg Avatar answered Jan 08 '23 01:01

georg