Javascript Tree Sort and Level

Creates a tree array from a flat array. Tree nodes are numbered by their level in the tree and alpha sorted by their id.

by jarosciak

JavaScript

// STEP 1: Get a flat array of objects.

/* A flat (1 dimensional) array, which can later be turned into a tree, since each array item has an id and parent property. */
var x = [
{"id": "A", "parent": 0, "date": "2020-12-30T11:00:01-01:00",children: []}, // 2 immediate children, root node
{"id": "B", "parent": "A", "date": "2020-12-30T11:00:01-01:00", children: []}, // 2 immediate children
{"id": "C", "parent": "B", "date": "2020-12-30T11:00:01-01:00", children: []}, // 2 immediate children
{"id": "D", "parent": "C", "date": "2020-12-30T11:00:01-01:00", children: []}, // 2 immediate children
{"id": "E", "parent": "C", "date": "2020-12-30T11:00:01-01:00", children: []}, // 2 immediate children
];


// STEP 2: Turn the flat array into a tree (hierarchical) array.

function tierData (arr) {
/* 
	Params: 
		@arr = flat array. Each array item is an object containing id, parent, and children properties.
		
	Description: 
		Takes a flat array and turns into into a tree (hierarchical) array.
*/
	for (var i = 0; i < arr.length; i++) {
		arr.forEach(function (n) {
			if (n.parent === arr[i].id) {
				arr[i].children.push(n);
			}			
		});
	}
	return arr.filter(function (n) { return n.parent === 0 }); // Only return root nodes and their children, children's children, etc.
}

var td = tierData(x);
//console.log(td);


// STEP 3: Assign a "level" property to each tree level. Numeric sort tree items for each level in the tree.

function treeSortAndLevel (treeArr,flatArr,flatIndex) {
/* 
	Params: 
		@treeArr = A tree (hierarchical) array, created from a flat array using the tierData fn.
		@flatArr = A flat array on which @treeArr is based.
		@flatIndex = DON'T PASS AN ARG. This is assigned a value by subsequent recursive fn calls. 
		
	Description: 
		Returns a tree which is numeric sorted at each level and each tree node is assigned a level property value, starting with root node(s) level = 0.
*/
	// If not provided (ie the fn's first call), create an indexer for the flat...