Outline numbering for an object tree

Josh Sherman
3 min read
Software Development JavaScript

Last week I had talked about a layout dilemma that my buddy Justin was having. This reminded me of an issue that programming challenge he hit me with a few months prior. The challenge was to take an object tree and generate the proper outline numbering for it. The object tree was hierarchical with an indefinite number of children and nesting levels. The object tree looks something like this:

var data = [{
  title: "Lorem",
    children: [{
      title: "Ipsum"
  }, {
    title: "Dolor",
    children: [{
      title: "Sit"
    }, {
      title: "Amet"
    }]
  }]
}, {
  title: "Consectetur",
  children: [{
    title: "Adipiscing"
  }, {
    title: "Elit"
  }]
}];

That’s a Javascript object because FUCK YEAH JAVASCRIPT! Also because Justin was working with Javascript and it seemed fair to work the problem out as such. Now that we have our object, let’s take a look at what the desired output is. If you’re not familiar with an outline, each section is numbered like 1.0 or 1.2.3 depending on how many levels deep it is. With the aforementioned object we would be expecting an output like:

1.0 Lorem
1.1 Ipsum
1.2 Dolor
1.2.1 Sit
1.2.2 Amet
2.0 Consectetur
2.1 Adipiscing
2.2 Elit

The challenge didn’t get into indenting based on nesting, but that’s definitely something that could improved. The code itself relies on on recursion since the object can have any number of children which could have any number of children,

outlineNumber = function(items, lastId) {
  var currentId = lastId;

  items.forEach(function(item) {
    currentId[currentId.length - 1]++;

    console.log(currentId.length == 1 ? currentId + '.0' : currentId.join('.'), item.title);

    if (item.children && item.children.length) {
      var childId = lastId.slice(0);
      childId.push(0);
      outlineNumber(item.children, childId);
    }
  });
};

outlineNumber(data, [0]);

The gist is that I start with an array with a single element of zero. For each pass through the function, the last number in the array is incremented. For each increase in nesting, another number is added to the end. Then the array of numbers is combined together (with periods in between) to create the outline number. There’s also some magic to toss in “.0” to the top level numbers.

Got a better way to attack this one? Comment below!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles