user12130378
user12130378

Reputation:

why two function gives different output having same approch?

below function gives incorrect output

function searchFn(obj, searchText) {
    let result;
    if (obj.name === searchText) return obj;
    if (obj['children'] && obj['children'].length > 0) {
        obj['children'].forEach((i) => {
                 result = searchFn(i, searchText);
                 return result
        })
    }
    return result || null
}

Below function gives correct out

function searchFn(object, searchText) {
    var result;
    if (object.name === searchText) return object;
    (object.children || []).some((o) =>{
        result = searchFn(o, searchText)
        return result
    });
    return result || null;
}

why it is happening ?I used on forEach in first approch and some function in second .

any body explain why it is happening?

let tree = { name: "A", children: [{ name: 'A-1', children: [{ name: "A-1-A" }, { name: "A-1-B" }] }, { name: 'B-1', children: [{ name: "B-1-A", children: [{ name: "B-11-A" }, { name: "B-11-B" }] }, { name: "B-1-B" }] }] };


console.log(searchFn(tree, 'A-1'));

expected output is

{ name: 'A-1', children: [{ name: "A-1-A" }, { name: "A-1-B" }] }

is first function i am getting null

second function gives correct output why ?

both function using recursion.

Upvotes: 0

Views: 31

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370779

The return value of forEach is ignored. In your first code, you're iterating through the whole structure recursively, but the result variable returned inside the forEach doesn't do anything - at the end, outside the loop, the return result || null will return only the result of calling searchFn for the final item in obj.children.

If you want to be able to return a recursive call directly, either use your .some method to short-circuit, or use a for loop, which you can return inside of to terminate the parent function:

function searchFn(object, searchText) {
  if (object.name === searchText) return object;
  if (!object.children) return;
  for (const child of object.children) {
    const result = searchFn(o, searchText)
    if (result) return result;
  }
}

Upvotes: 1

SpiritOfDragon
SpiritOfDragon

Reputation: 1432

forEach executes without breaking the loop. As you are assigning result, it always receives the last value of the item.

on the other hand .some will stop the loop when some condition matches and returns true. so here result will receive the value when the condition matches and just before exiting the loop

Upvotes: 1

Related Questions