By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – Convert hierarchical text (with hyphens) into flare data for D3.js
JavaScript

Javascript – Convert hierarchical text (with hyphens) into flare data for D3.js

Admin
Last updated: 2024/02/10 at 2:43 PM
Admin
Share
4 Min Read
Convert hierarchical text (with hyphens) into flare data for D3.js

Problem:

Trying to create the following:

Contents
Problem:Solution:

enter image description here

…using this text data:

var inputText = `
- a
  - - b_1
  - - - c_1
  - - - c_2
- b
  - - b_2
  - - - d_1
  - - - d_2
`;

Here is the code:

JS:

function parseHierarchicalText(text) {
var lines = text.split('\n');

function parseNode(index, depth) {
    var node = {
        name: lines[index].trim().replace(/-/g, '').trim(),
        children: []
    };
    index++;
    while(index < lines.length && lines[index].lastIndexOf('-') / 2 > depth) {
        var result = parseNode(index, depth + 1);
        node.children.push(result.node);
        index = result.index;
    }
    return {
        node: node,
        index: index
    };
}
var flareData = [];
var index = 0;
while(index < lines.length) {
    var result = parseNode(index, 0);
    flareData.push(result.node);
    index = result.index + 1;
}
return {
    name: 'Root',
    children: flareData
};
}
var inputText = `
- a
  - - b_1
  - - - c_1
  - - - c_2
- b
  - - b_2
  - - - d_1
  - - - d_2
`;
var data = parseHierarchicalText(inputText);
// Set the dimensions and margins of the diagram
var margin = {
        top: 20,
        right: 90,
        bottom: 30,
        left: 90
    },
    width = 800 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;
// Appending svg to the dendrogram div
var svg = d3.select("#dendrogram").append("svg").attr("width", width + margin.left + margin.right).attr("height", height + margin.top + margin.bottom).append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Create a hierarchical cluster layout
var hierarchy = d3.hierarchy(data, function(d) {
    return d.children; // specify children accessor
});
var cluster = d3.cluster().size([height, width - 100]);
// Assigns the x and y position for the nodes
var root = cluster(hierarchy);
// Draw links between nodes
svg.selectAll('path').data(root.links()).enter().append('path').attr('class', 'link').attr('d', d3.linkHorizontal().x(function(d) {
    return d.y;
}).y(function(d) {
    return d.x;
}));
// Draw nodes
var nodes = svg.selectAll('g.node').data(root.descendants()).enter().append('g').attr('class', function(d) {
    return 'node' + (d.children ? ' node--internal' : ' node--leaf');
}).attr('transform', function(d) {
    return 'translate(' + d.y + ',' + d.x + ')';
});
nodes.append('circle').attr('r', 7);
nodes.append('text').attr('dy', '.35em').attr('x', function(d) {
    return d.children ? -13 : 13;
}).style('text-anchor', function(d) {
    return d.children ? 'end' : 'start';
}).text(function(d) {
    return d.data.name;
});

But instead it produces this:

enter image description here

Here is a codepen.

Solution:

FWIW, here’s a function that appears to parse your input correctly:

function parseHierarchicalText(text) {
    let root = {name: 'root', children: []}
    let stack = [root]

    for (let line of text.trim().split('\n')) {
        let parts = line.match(/([- ]+)(.+)/)
        let level = parts[1].match(/-/g).length
        while (level < stack.length)
            stack.pop()
        let node = {name: parts[2], children: []}
        stack.at(-1).children.push(node)
        stack.push(node)
    }

    return root
}

//

var inputText = `
- a
  - - b_1
  - - - c_1
  - - - c_2
- b
  - - b_2
  - - - d_1
  - - - d_2
`;


r = parseHierarchicalText(inputText)
console.log(JSON.stringify(r, 0, 4))

Expand snippet

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article React firebase error: where' is not defined query call firebase in react Javascript – React firebase error: where’ is not defined query call firebase in react
Next Article How to set the value of two dropdowns by clicking on a table row? Javascript – How to set the value of two dropdowns by clicking on a table row?
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?