1

i have a recursive function to find key and return his value, this is my code

$scope.findSelected = function (object, name){
            //var key = '';
            for (var i =0 ; i< object.length; i++){
               var children =object[i];
                var vName =children.Value.Name;
                if(vName=== name ){
                    var key=children.Value.Key;
                    break;


                }else {
                     key = $scope.findSelected(children.Children, name);
                }
            }
            return key;
        };

where vName === name i have to return key, but not work the loop play again, I think I've any dodgy thing and function return unidentified

5
  • 1
    Notice that a return only returns from the current call of the function, not the uppermost recursive one? And break only breaks from the current loop, not all loops in your recursion? Commented May 13, 2015 at 15:05
  • if you inside recursion you need also check what return $scope.findSelected in else branch and if it return not undefined - also break loop Commented May 13, 2015 at 15:05
  • if someone can change my code to the function works properly Commented May 13, 2015 at 15:09
  • 1
    It's better if people teach you to find the problems yourself, so that you can fix your own code in the future. Commented May 13, 2015 at 15:12
  • so if someone can explain me more Commented May 13, 2015 at 15:19

1 Answer 1

6

Try the following. It checks at the end of each iteration if key has been set and if so will return it. This will also "bubble up" from lower levels of recursion. The search order is depth-first.

$scope.findSelected = function (object, name){
    var key;

    for (var i = 0; i < object.length; i++){
         var children =object[i];
         var vName = children.Value.Name;

         if(vName === name ){
              key = children.Value.Key;
         } else {
              key = $scope.findSelected(children.Children, name);
         }

         if(key) return key;
    }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.