Skip to content

Instantly share code, notes, and snippets.

@leobetosouza
Last active December 29, 2016 15:29
Show Gist options
  • Save leobetosouza/762a604fb9345f477ee9c730e2b13286 to your computer and use it in GitHub Desktop.
Save leobetosouza/762a604fb9345f477ee9c730e2b13286 to your computer and use it in GitHub Desktop.
Reduce to ordened tuples of group and ordened values with lodash help
[
{ordernation: 2, category : 'A'}, {ordernation: 2, category : 'B'},
{ordernation: 1, category : 'A'}, {ordernation: 1, category : 'B'},
{ordernation: 3, category : 'C'}
]
.reduce(function (acc, it) {
let tuple = acc.find(tuple => tuple[0] === it.category);
if (tuple) {
let list = tuple[1];
list.splice(_.sortedIndexBy(list, it, 'ordernation'), 0, it)
} else {
let newTuple = [it.category, [it]];
acc.splice(_.sortedIndexBy(acc, newTuple, '0'), 0, newTuple)
}
return acc;
}, [])
//[
// ['A', [{ordernation: 1, category : 'A'}, {ordernation: 2, category : 'A'}]],
// ['B', [{ordernation: 1, category : 'B'}, {ordernation: 2, category : 'B'}]],
// ['C', [{ordernation: 3, category : 'C'}]]
//]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment