ProfK
ProfK

Reputation: 51064

Underscorejs 'find' not working as expected

I use the following code, in a nodejs app, to build a tree from an array of database rows that form an adjacency list:

// Lay out every node in the tree in one flat array.
var flatTree = [];
_.each(rows, function(row) {
    flatTree.push(row);
});

// For each node, find its parent and add it to that parent's children.
_.each(rows, function(row) {
    // var parent = _.find(flatTree, function(p) {
    //     p.Id == row.ParentId;
    // });
    var parent;
    for (var i = 0; i < flatTree.length; i++){
        if (flatTree[i].Id == row.ParentId) {
            parent = flatTree[i];
            break;
        }
    };
    if (parent){
        if (!parent.subItems) {
            parent.subItems = [];
        };
        parent.subItems.push(row);
    }
});

I expect the commented out _.find call to do exactly the same as what the work-around for loop below it does, but _.find never finds the parent node in flatTree, while the for loop always does.

Similarly, a call to _.filter just doesn't work either, while the substitute loop does:

// var rootItems = _.filter(flatTree, function (node) {
//     //node.ParentId === null;
//     node.NoParent === 1;
// })
var rootItems = [];
for (var i = 0; i < flatTree.length; i++){
    if (flatTree[i].ParentId == null){
        rootItems.push(flatTree[i]);
    }
}

I am using the underscore-node package, but have tried and had the same results with the regular underscore package.

Upvotes: 0

Views: 502

Answers (1)

Tushar
Tushar

Reputation: 87203

Just missed the return.

var parent = _.find(flatTree, function(p) {
    return p.Id == row.ParentId; // Return true if the ID matches
    ^^^^^^ <-- This
});

In your code nothing is returned, so by default undefined will be returned and parent will not contain any data.

Upvotes: 3

Related Questions