0

This is an algorithm posted by Nina Scholz, which converts an array of sorted elements with level property to a tree-like structure:

link: https://stackoverflow.com/a/44519904/8252267

let exampleList = [{
  id: 1,
  level: 1
}, {
  id: 2,
  level: 2
}, {
  id: 3,
  level: 2
}, {
  id: 4,
  level: 3
}, {
  id: 5,
  level: 3
}, {
  id: 6,
  level: 1
}]

function getTree(array) {
  var levels = [{}];
  array.forEach(function(a) {
    levels.length = a.level;
    levels[a.level - 1].nodes = levels[a.level - 1].nodes || [];
    levels[a.level - 1].nodes.push(a);
    levels[a.level] = a;
  });
  return levels[0].nodes;
}

/*
result:

[
  {
    "id": 1,
    "level": 1,
    "nodes": [
      {
        "id": 2,
        "level": 2
      },
      {
        "id": 3,
        "level": 2,
        "nodes": [
          {
            "id": 4,
            "level": 3
          },
          {
            "id": 5,
            "level": 3
          }
        ]
      }
    ]
  },
  {
    "id": 6,
    "level": 1
  }
]
*/


Is it Nina's original creation, or is it a well known algorithm for a (probably) quite common task? I found an answer here, where the algorithm (to create nested html list) seemed quite similar.

Is there a name for this algorithm?

HynekS
  • 2,738
  • 1
  • 19
  • 34

0 Answers0