0

First thank you in advance for any responses to this problem I am having. I am new to JS and feel that this code should be pretty straight forward, but it is not working as intended.

I want to search through these objects in the array by name, and if the name (that is obtained through the prompt) is found in the array, I want to display the id of that object.

if I type 'Jef' into the prompt, I get the ID; but if I type 'Steve' or 'Ryan' I get nothing. I also noticed that the loop seems to end no matter what I type without a break being added. I think the loop is breaking, but I don't know what is causing it to break before the 'If' condition is met. Please help!

var array = [{
    name: 'Jef',
    age: 29,
    id: '000'
  }, {
    name: 'Steve',
    age: 28,
    id: '001'
  },
  {
    name: 'Ryan',
    age: 28,
    id: '002'
  }
];

var i;

for (i = 0; i < array.length; i++) {
  if (prompt() == array[i].name) {
    console.log(array[i].id)
  }
}
spanky
  • 2,768
  • 8
  • 9
  • When you type the names in the defined order, I get all the expected responses. Was there a reason you wanted the prompt in a loop? The loop doesn't end for me as you describe. – spanky Aug 29 '17 at 17:42
  • Maybe you checked the `Prevent this page from creating additional dialogs` checkbox in the prompt window? – spanky Aug 29 '17 at 17:43

2 Answers2

1

The way you are doing it is close. You just need to put the prompt() outside the loop. Once you have the input to search, you then loop through your whole array of objects.

For example:

var nameInput = prompt();
for (i =0; i < array.length; i++){
    if (nameInput == array[i].name) {
       console.log(array[i].id)
    }
}

Small explanation

Since your prompt is in a loop that also loops your array of objects, there can only be 1 "correct" answer at that given prompt point - whatever index (array[i].name) the loop is currently on.

To see more of what I mean run your current code and type jef the first time the prompt comes up, Steve the second time, and Ryan the third time- this way gets your IDs, but is probably not your intended outcome.

Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
0

Try this. You need to sort through your array and perform a strong match, then return the ID.

function NameExists(strName,objectArray)
{
    //convert to lower for type sensitive
    strName = strName.toLowerCase();
    for(var i = 0; i <objectArray.length; i++)
    {
        //convert to lower for type sensitive
        var comparison = objectArray[i].Name.toLowerCase();

        if(comparison.match(strName)==comparison)
            return objectArray[i].id;
    }
}
Matt
  • 1,062
  • 1
  • 8
  • 11
Jacob Gaiski
  • 516
  • 3
  • 10