Turn flat array into nested array using javascript

javascript flatten(array of objects)
flatten(array javascript es6)
flatten object javascript
array.flat is not a function
javascript flatten array of objects by key
javascript convert array to array of array
reduce array of arrays into array
javascript aggregate array of objects

I am looking to turn this flat array into an nested array but it keeps returning as empty. Not sure how to solve this one or what I am missing but this is driving me crazy.

Flat array:

var names =[
{ name: 'b', parent: 'Brown' },
{ name: 'a', parent: 'Brown' },
{ name: 'h', parent: 'Green' },
{ name: 'c', parent: 'Green' },
];

Desired output of array:

[{
    name: 'Brown',
    children: [{
            name: 'a',
            children: []
        },
        {
            name: 'b',
            children: []
        }
    ]
}, {
    name: 'Green',
        children: [{
                name: 'h',
                children: []
            },
            {
                name: 'c',
                children: []
            }
        ]
    }
}]

Js:

function getNestedChildren(arr, parent) {
    var children = [];
    for(var i =0; i < arr.length; ++i) {
        if(arr[i].parent == parent) {
            var grandChildren = getNestedChildren(arr, arr[i].name)

            if(grandChildren.length) {
                arr[i].children = grandChildren;
            }
            children.push( arr[i]);
        }
    }
    return children;
}
var nest = getNestedChildren(names, names.parent);
console.log( nest);

var names =[
{ name: 'b', parent: 'Brown' },
{ name: 'a', parent: 'Brown' },
{ name: 'h', parent: 'Green' },
{ name: 'c', parent: 'Green' },
{ name: 'j', parent: 'Brown' }
];

function groupBy(arr, f) {
  return arr.reduce((r, v, i, a, k = f(v)) => ((r[k] || (r[k] = [])).push(v), r), {});
}

function nestArray(array){
  var newArray=[],
      resultGrouped = groupBy(names, function(c) {
    return c.parent
  });
  
  for (var key in resultGrouped){
    var item=resultGrouped[key];
    
    newArray.push({
      name:key,
      children:item.map(function(map){
        delete map.parent;
        map.children=[];
        return map;
      })
    });
  }
  
  return newArray;
}
console.log(nestArray(names));

Array.prototype.flat(), These are the three known ways to merge multidimensional array into a single array. I am looking to turn this flat array into an nested array but it keeps returning as empty. Not sure how to solve this one or what I am missing but this is driving me crazy. Flat array: var names

You can create a new object, for each item assign an array to a key with the parent name, and concatenate the item to that array

var names =[
{ name: 'b', parent: 'Brown' },
{ name: 'a', parent: 'Brown' },
{ name: 'h', parent: 'Green' },
{ name: 'c', parent: 'Green' },
];

const getGroup=(groups, parent) => {
  let group = groups.find(g=>g.parent===parent);
  if(!group){
    group=({parent,children:[]});
    groups.push(group);
  }
  return group;
}

let  grouped = []
 names.forEach(item=> getGroup(grouped,item.parent).children.push(item))
 
                             
console.log(grouped)

How to flatten nested array in javascript?, The great thing is that this method also works beyond 1 level deep. You simply have to set the appropriate depth parameter to flatten deeper nested arrays. const  Flattening multidimensional Arrays in JavaScript By @loverajoel on Feb 7, 2016 These are the three known ways to merge multidimensional array into a single array.

So for starters, you need to loop through the names and send each parent to your getNestedChildren() function.

var names =[
    { name: 'b', parent: 'Brown' },
    { name: 'a', parent: 'Brown' },
    { name: 'h', parent: 'Green' },
    { name: 'c', parent: 'Green' },
];

var nest = [];

for (var i = 0; i < names.length; i++) {
    nest.push(getNestedChildren(names, names[i].parent));
} 

Also your getNestedChildren() is currently trying to modify and send back the old names array. I'd suggest creating a new object instead and send back the object with the children on it.

function getNestedChildren(arr, parent) {
    var children = [];
    var parentObj = {};
    parentObj.name = parent;
    for(var i =0; i < arr.length; ++i) {
        if(arr[i].parent == parent) {
            children.push(getNestedChildren(arr, arr[i].name));
        }
    }
    parentObj.children = children;
    return parentObj;
}

Merge/flatten an array of arrays, JavaScript Array: Exercise-21 with Solution. Write a JavaScript program to flatten a nested (any depth) array. If you pass shallow, the array will  So far, all the arrays we’ve dealt with have been “flat” arrays; each array element contains a single value, such as a number, string, or object. However, like most programming languages, JavaScript lets you create arrays inside arrays, known as nested arrays. In a nested array, the elements of one array are themselves arrays. For example:

Flattening an Array, a Performance Test - DEV Community ‍ ‍ , Create a nested array recursively in Javascript. Let's say you have an array like this: [ {id: 1, title: 'hello', parent: 0}, {id: 2, title: 'hello', parent: 0},  The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both into one method is slightly more efficient.

Underscore.js, Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff. You can make a tax-deductible  While this syntax is convenient and easy to remember, flattening arrays of arrays of arrays doesn't work here - it's also slow on huge arrays. For a more performant solution, check out this StackOverflow answer for a similar answer in JavaScript - it does the same thing but is faster and works on deeply nested arrays.

Flattening multidimensional Arrays in JavaScript, So I need to flatten each array in the array in order " given a nested array or arrays, return a new, flat array with all the elements of all the nested  JavaScript is forgiving so it won’t crash our program, instead it does know how to concatenate strings, so it will convert everything into a string. A slightly less common approach is to use the join() method. By default it adds a comma to resulting values, though you can also specify that it add nothing or some other separator value. What if

Comments
  • var nest = getNestedChildren(names, names.parent); what is names.parent? undefined?
  • you have to loop through the names and call parent for each one names[0].parent (otherwise its undefined)
  • I am trying to get to the root level of the array. Any thoughts?
  • @user992731 use 0 to get the root level. See my answer below
  • Also, this might be interesting for you: how-to-group-an-array-of-objects-by-key (copied wrong link first, edited)
  • Your results don't look like the OP's desired result.