Created
June 18, 2018 08:01
-
-
Save Ma-ve/9e51ab5c40577c71c50d13edaa7f302e to your computer and use it in GitHub Desktop.
[JS] DossierItem LinkedTo based on list of array of external ids
This file contains hidden or 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
function getLinkedToInfoByArrayOfIds(ids) { | |
if(ids.length < 1) { | |
return []; | |
} | |
var group = { | |
'person' : 'relation', | |
'organization' : 'relation', | |
'project' : 'project', | |
'sales' : 'sales' | |
}; | |
var linkedTo = { | |
'person' : 'person_id', | |
'organization' : 'organization_id', | |
'project' : 'project_id', | |
'sales' : 'sales_id' | |
}; | |
// Group them by their matched grouping. [ 'person:abc', 'org:abc' => ['relation' => ['person:abc', 'org:abc'] ] | |
var groupedData = {}; | |
for(var i = 0; i < ids.length; i++) { | |
var split = ids[i].split(':'); | |
if(!(group[split[0]] in groupedData)) { | |
groupedData[group[split[0]]] = []; | |
} | |
groupedData[group[split[0]]].push(ids[i]); | |
} | |
// Get the highest count of groupedData (['relation' => ['person:abc', 'org:abc'], 'project' => ['project:abc']] returns 2 | |
var max = 0; | |
var keys = Object.keys(groupedData); | |
for(var j = 0; j < keys.length; j++) { | |
if(groupedData[keys[j]].length > max) { | |
max = groupedData[keys[j]].length; | |
} | |
} | |
// Loop the maximum times of occurences, then assign items to each array, and unset them for the next loop | |
var result = {}; | |
for(var k = 0; k < max; k++) { | |
for(var j = 0; j < keys.length; j++) { | |
if(groupedData[keys[j]].length) { | |
var id = groupedData[keys[j]].shift(); | |
var split = id.split(':'); | |
var key = linkedTo[split[0]]; | |
if(!(k in result)) { | |
result[k] = {}; | |
} | |
result[k][key] = id; | |
} | |
} | |
} | |
return result; | |
} | |
var result = getLinkedToInfoByArrayOfIds([ | |
'organization:111', | |
'person:222', | |
'project:333', | |
'sales:444', | |
'person:555', | |
'project:666' | |
]); | |
// Expected: Array[3] - [ {org_id: org:111, project_id: project:333, sales_id: sales:444} , { person_id: person:222, project_id: project:666 } , { person_id: person: 555 } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment