JavaScript Array Sorting by Level



In this article, we will learn array sorting by level in JavaScript, creating a hierarchical tree structure from a flat array is a common challenge when dealing with relational data. This is a common task when dealing with hierarchical data, such as organizational charts, category trees, or file systems, where relationships like parent-child need to be represented.

Problem Statement

We have an array of objects representing nodes with _id, level, and parentId properties. Our goal is to transform this array into a tree structure where nodes are nested as children under their respective parents. The elements with the highest level would be the main array, with their children as subarray.

If the input array is given by ?

const arr = [
   {
      _id: 100,
      level: 3,
      parentId: null,
   },
   {
      _id: 101,
      level: 2,
      parentId: 100,
   },
   {
      _id: 102,
      level: 2,
      parentId: 100,
   },
   {
      _id: 103,
      level: 2,
      parentId: 100,
   },
   {
      _id: 104,
      level: 1,
      parentId: 101,
   },
   {
      _id: 105,
      level: 1,
      parentId: 102,
   },
   {
      _id: 106,
      level: 1,
      parentId: 101,
   },
   {
      _id: 107,
      level: 1,
      parentId: 103,
   },
   {
      _id: 108,
      level: 1,
      parentId: 102,
   },
   {
      _id: 109,
      level: 1,
      parentId: 103,
   }
];

Then the output structure should be something like ?

                                          100
                                           |
                           ------------------------------
                           |                |                  |
                          101              102            103
                        -------          ------           ------
                          |     |          |    |               |    |
                       104   106        105  108       107   109

The prepareTree Function

The prepareTree function takes a flat array of objects and constructs a hierarchical tree by nesting child nodes under their respective parent nodes based on the parentId. It efficiently organizes the data by iterating through the array and dynamically building the tree structure.

following are the steps for array sorting by level in JavaScript ?

  • Initialization
    • A utility object obj is created to map _id values to nodes.
    • The res variable holds the root node of the tree.
  • Iterating Through the Array
    • For each element in the array, a children property is initialized.
    • If the node's parentId matches the root, it becomes the root node (res).
    • Otherwise, it is added to its parent's children array.
  • Returning the Tree
    • The function returns the root node, now containing nested children for all relationships.

Iterates over the array of nodes using the forEach() method ?

arr.forEach(el => {
      el.children = obj[el._id] && obj[el._id].children;
      obj[el._id] = el;
      if (el.parentId === root) {
         res = el;
      }

Object.create() method creates a new object to store node mappings ?

const obj = Object.create(null);

Adding a node to the children array of its parent using the .push() method ?

obj[el.parentId].children.push(el);

JavaScript code to sort array by level

Below is the JavaScript code for array sorting by level:

const arr = [{
   _id: 100,
   level: 3,
   parentId: null,
},
{
   _id: 101,
   level: 2,
   parentId: 100,
},
{
   _id: 102,
   level: 2,
   parentId: 100,
},
{
   _id: 103,
   level: 2,
   parentId: 100,
},
{
   _id: 104,
   level: 1,
   parentId: 101,
},
{
   _id: 105,
   level: 1,
   parentId: 102,
},
{
   _id: 106,
   level: 1,
   parentId: 101,
},
{
   _id: 107,
   level: 1,
   parentId: 103,
},
{
   _id: 108,
   level: 1,
   parentId: 102,
},
{
   _id: 109,
   level: 1,
   parentId: 103,
}];
const prepareTree = (arr = [], root = null) => {
   let res;
   const obj = Object.create(null);
   arr.forEach(el => {
      el.children = obj[el._id] && obj[el._id].children;
      obj[el._id] = el;
      if (el.parentId === root) {
         res = el;
      }
      else {
         obj[el.parentId] = obj[el.parentId] || {};
         obj[el.parentId].children = obj[el.parentId].children || [];
         obj[el.parentId].children.push(el);
      }
   });
return res;
};
console.log(JSON.stringify(prepareTree(arr), undefined, 4));

Output

{
   "_id": 100,
   "level": 3,
   "parentId": null,
   "children": [
      {
         "_id": 101,
         "level": 2,
         "parentId": 100,
         "children": [
            {
               "_id": 104,
               "level": 1,
               "parentId": 101
            },
            {
               "_id": 106,
               "level": 1,
               "parentId": 101
            }
         ]
      },
      {
         "_id": 102,
         "level": 2,
         "parentId": 100,
         "children": [
            {
               "_id": 105,
               "level": 1,
               "parentId": 102
            },
            {
               "_id": 108,
               "level": 1,
               "parentId": 102
            }
         ]
      },
      {
         "_id": 103,
         "level": 2,
         "parentId": 100,
         "children": [
            {
               "_id": 107,
               "level": 1,
               "parentId": 103
            },
            {
               "_id": 109,
               "level": 1,
               "parentId": 103
            }
         ]
      }
   ]
}

Time Complexity: The time complexity is O(n), where n is the number of elements in the array since each node is processed once.
Space Complexity: The space complexity is O(n), as the tree structure and auxiliary obj object both store n nodes.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-01-06T15:51:00+05:30

848 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements