Skip to content

Instantly share code, notes, and snippets.

@varunrayen
Last active June 25, 2021 11:26
Show Gist options
  • Save varunrayen/a9a17f7aacb81823978249a61a0d8f97 to your computer and use it in GitHub Desktop.
Save varunrayen/a9a17f7aacb81823978249a61a0d8f97 to your computer and use it in GitHub Desktop.
Sorting a category list from a flat database for insert into a hierarchy-constrained one
module.exports = function sortCategoriesForInsert (inputJson) {
let dataTree = function (inputJson, root) {
var r = [], o = {};
inputJson.forEach(function (a) {
o[a.id] = { data: a, children: o[a.id] && o[a.id].children };
if (a.parent_id === root) {
r.push(o[a.id]);
} else {
o[a.parent_id] = o[a.parent_id] || {};
o[a.parent_id].children = o[a.parent_id].children || [];
o[a.parent_id].children.push(o[a.id]);
}
});
return r;
}(inputJson, null)
let sortedDataTree = dataTree.reduce(function traverse(r, a) {
return r.concat(a.data, (a.children || []).reduce(traverse, []));
}, [])
return sortedDataTree
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment