Unflatten a multi level flat array of objects. Many times we need to convert flat array, into hierarchical structure. And If flat array size is too big then it will be slow with general recursive function. Below method is more efficient for large data.

function unflattenArray(inputArray, objectKeyName, objectParentKeyName, childrenKeyName) {
    var result = [], indexedObjects = {}, arrObj, resultObj;

    // First map the nodes of the array to an object -> create a hash table.
    for (var i = 0, len = inputArray.length; i < len; i++) {
        arrObj = inputArray[i];
        indexedObjects[inputArray[i][objectKeyName]] = arrObj;
        indexedObjects[inputArray[i][objectKeyName]][childrenKeyName] = [];
    }

    for (var propTemp in indexedObjects) {
        if (indexedObjects.hasOwnProperty(propTemp)) {
            resultObj = indexedObjects[propTemp];
            if (resultObj[objectParentKeyName]) {
                indexedObjects[resultObj[objectParentKeyName]][childrenKeyName].push(resultObj);
            } else {
                result.push(resultObj);
            }
        }
    }
    return result;
}

// Call the function like below
unflattenArray(inputArray, 'id', 'parentId', 'children');

 

Discussion
9 X 3
** To prevent abusing comments from publishing, posted comments will be reviewed and then published!
 Mritunjay Kumar
Works at Mindfire Solutions

I mostly work with C#, ASP.NET, MVC, WCF, Web API, Entity FrameWork, MS Sql.

More under this category...
Deselect radio button through javascript (jQuery)
All under this category...