Tree from flat

Benchmark created on


Setup

const data = [
	{ id: 5, parent_id: 1 },
	{ id: 1, parent_id: null },
	{ id: 2, parent_id: 1 },
	{ id: 6, parent_id: 1 },
	{ id: 3, parent_id: 2 },
	{ id: 8, parent_id: 1 },
	{ id: 4, parent_id: 2 },
	{ id: 7, parent_id: 3 }
];


function buildTreeMine(data) {
	const tree = {};
	const lookup = {};

	for (const item of data) {
		lookup[item.id] = item;
		lookup[item.id].children = [];
	}

	for (const item of data) {
		if (typeof lookup[item.parent_id] === 'undefined') {
			tree[item.id] = item;
		}
		else {
			lookup[item.parent_id].children.push(item);
		}
	}

	return Object.values(tree);
}



const createTree = (data, parent_id = null) => {

	// Create an empty array to hold the tree structure
	let tree = [];

	// Loop through the data to find the children of the parent_id
	data.filter(item => item.parent_id === parent_id).forEach(item => {

		// Recursively create the tree structure for the children
		let children = createTree(data, item.id);

		// If the children array is not empty, add it to the item
		if (children.length) {
			item.children = children;
		}

		// Add the item to the tree array
		tree.push(item);
	});

	// Return the tree array
	return tree;
};



const createTreeFAST = (data, parent_id = null) => {
	let tree = [];
	let children = [];
	for (let item of data) {
		if (item.parent_id === parent_id) {
			children = createTreeFAST(data, item.id);
			if (children.length) {
				item.children = children;
			}
			tree.push(item);
		}
	}
	return tree;
};

const createTreeFASTER = (data, parent_id = null) => {
	let tree = [];
	let children = [];
	for (let i = 0; i < data.length; i++) {
		if (data[i].parent_id === parent_id) {
			children = createTreeFASTER(data, data[i].id);
			if (children.length) {
				data[i].children = children;
			}
			tree.push(data[i]);
		}
	}
	return tree;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Mine
buildTreeMine(data);
ready
M1
createTree(data, null);
ready
M2_FAST
createTreeFAST(data, null);
ready
M3_FASTER
createTreeFASTER(data, null);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.