JSFiddle - React, Tailwind, and code Playground

Flatten children

by Hugo Carneiro

JavaScript

function flatten(arr) {
  return arr.reduce(function(flat, next) {
    return flat.concat(Array.isArray(next.children) && next.children.length ? flatten(next.children) : next);
  }, []);
}

var data = [
	{
    title: 'Header',
    children: [{
      title: 'Paragraph',
      children: []
    }],
  },
  {
    title: 'Container',
    children: [{
      title: 'Paragraph',
      children: []
    }]
  }
];

var flat = flatten(data);
console.log(flat);

/* EXPECTED RESULT */
/*
[
	{
    title: 'Header',
    children: [{
      title: 'Paragraph',
      children: []
    }],
  },
  {
    title: 'Paragraph',
    children: []
  },
  {
    title: 'Container',
    children: [{
      title: 'Paragraph',
      children: []
    }]
  },
  {
    title: 'Paragraph',
      children: []
  }
];
*/