Last active
June 6, 2018 13:02
-
-
Save karolk/53bcb8d0d75bfc9ec494d1e0a0140fc4 to your computer and use it in GitHub Desktop.
Graph data by sequential prop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Given a list with data containing sequential property such as year of birth, age, size | |
// Create a graph containing elements groupped by that property with ids of next nodes | |
// Output example | |
{ | |
'1': {list: [{size: 1}, {size: 1}], previous: undefined, next: '3'}, | |
'3': {list: [{size: 3}], previous: '1', next: '4'}, | |
'4': {list: [{size: 4}], previous: '3', next: undefined}, | |
} | |
const graphBy = (items, seqeuentialProp) => { | |
const groupped = items.reduce((acc, elem) => { | |
if (!(elem[seqeuentialProp] in acc)) {acc[elem[seqeuentialProp]] = {list: []}} | |
acc[elem[seqeuentialProp]].list.push(elem) | |
return acc; | |
}, {}); | |
const sorted = Object.keys(groupped).sort((a, b) => parseInt(a) - parseInt(b)) | |
sorted.forEach((prop, index) => { | |
const prev = sorted[index - 1]; | |
const next = sorted[index + 1]; | |
Object.assign(groupped[prop], {prev, next}); | |
}); | |
return groupped; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment