Link to home
Start Free TrialLog in
Avatar of Isaac
IsaacFlag for United States of America

asked on

undefined returned from function

I don't understand why I get undefined below.

var index = -1;
var proj = "893x-3owe34p";

alert(getIndex(proj));
function getIndex(val){
var filteredObj = jsonFile.Result.Contracts.find(function(item, i) {
  //console.log(item.Plan.Identification.PlanNumber)
  if (item.Plan.Identification.PlanNumber == val) {
    index = i;
    return index;
  }
  //return index;
});

  }

Open in new window


https://jsfiddle.net/isogunro/681j6nk6/1/
Avatar of Isaac
Isaac
Flag of United States of America image

ASKER

I solved my issue with the code below but I would still like to know why the above didn't work.

function getIndex(val){        
	for (var x=0; x<jsonFile.Result.Contracts.length; x++){  
        if (jsonFile.Result.Contracts[x].Plan.Identification.PlanNumber == val) {
            var index = x;
          }
  }
  return index;
}

Open in new window

no such project "893x-3owe34p"
Avatar of Isaac

ASKER

Yes there is. "PlanNumber"
The last one in the Contracts array
SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
or maybe you want to do this

var index = -1;
var proj = "893x-3owe34p";

var item = getIndex(proj)

alert(index);
alert(item);

function getIndex(val) {
  var filteredObj = jsonFile.Result.Contracts.find(function(item, i) {
    console.log(item.Plan.Identification.PlanNumber)
    if (item.Plan.Identification.PlanNumber == val) {
      index = i;
      return item;
    }
  });
  return filteredObj;
}

Open in new window


https://jsfiddle.net/HainKurt/rbuzLto5/

it sets index  + returns found object...
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Isaac

ASKER

What I should get back is 5.
If it's a function, how come it can't return the index? Just curious
Or like this - a bit more concise
var proj = "893x-3owe34p";

var filteredObj = jsonFile.Result.Contracts.find(function(item, i) {
  return item.Plan.Identification.PlanNumber == proj
});

if (filteredObj) {
  index = jsonFile.Result.Contracts.indexOf(filteredObj);
  console.log(index);
}

Open in new window

You can - but you weren't
Your return was inside the find() function block not the getIndex() function block.

find() expects a true / false return based on whether the item was found or not - but this would end up with setting filteredObj to the found item - but you don't do anything with filteredObj and nothing is returned - hence the undefined.
Avatar of Isaac

ASKER

Thanks Guys!