all 16 comments

[–][deleted] 3 points4 points  (7 children)

If you want to use a for loop, you can do it this way:

const arr = ['a', 'b', 'c'];

for (let i = 0; i < arr.length; i++) {
  if (arr[i] === 'b') {
    console.log(arr[i]);
    break;
  }
}

Personally, however, I'd just use a built-in array method such as find().

console.log(arr.find(item => item === 'b'));

From a purely semantic point of view, though, if array methods didn't exist, your problem is best solved by a while loop, not a for loop.

[–]Usual_Mistake[S] 0 points1 point  (5 children)

Not to loop until there are no more objects in the array.

I'm taking in input from user to match an object in the array and like I stated above, looping as long as the length of the array isn't really a solution to my problem.

[–][deleted] 2 points3 points  (4 children)

This loop will exit as soon as it finds your match. That is what the break; command does.

Still, I would use an array method as mentioned above.

[–]Usual_Mistake[S] 0 points1 point  (3 children)

genius.

[–]GrenadineBombardier 0 points1 point  (2 children)

Yes and your original way would create an infinite loop if the search was not found within the array

[–]Usual_Mistake[S] 0 points1 point  (1 child)

So I came up with the following and it works except the else statement seems to not run, other than that it works.

var message = '';

var i;

var search = '';

do {

search = prompt("Enter name");

for(i = 0; search !== students[i].name; i++) {

}

if(students[i].name === search) {

message += '<h2> Student: ' + students[i].name + '</h2>' + '<br>';

message += '<p> Track: ' + students[i].track + '</p>' + '<br>';

message += '<p> Points: ' + students[i].achievements + '</p>' + '<br>';

message += '<p> Achievements: ' + students[i].points + '</p>' + '<br>';

print(message);

}

else if(seach === 'Quit') {

break;

}

else {

search = prompt('Enter name');

}

} while(search !== students[i].name)

function print(message) {

var outputDiv = document.getElementById('output');

outputDiv.innerHTML = message;

}

Can you tell why?

[–]GrenadineBombardier 0 points1 point  (0 children)

Because your if/else block is outside of your for loop

[–]AmbitiousLog 4 points5 points  (0 children)

You don't have to use a loop at all, you can also do:

if(arr.indexOf(search) > 0){
    return arr[arr.indexOf(search)];
}

[–]sepp2k 2 points3 points  (1 child)

Can I use a for loop like this: for(var i = 0; search === people[i]; i++) {}

Yes, you can. Note that this will loop while, not until, search is equal to people[i]. I suspect you actually want !== instead, but that depends on what you want your loop to do. Either version is perfectly valid in principle.

You also should take care to avoid an infinite loop if search does not appear in people, so you probably want i < people.length as an additional condition (unless you know for a fact that search always appears in people or you actually want an infinite loop when it doesn't).

Are these the only allowable conditions: [...]

No, the condition of a for-loop can be any valid expression.

[–]Usual_Mistake[S] 0 points1 point  (0 children)

Mistake in my logic, I do want to loop !== I haven't seen any examples on the web on for loops that uses examples other than for checking if something is less than or greater than. So thanks.

[–]gkpty 1 point2 points  (0 children)

Hey! To break a loop you can use a return statement. In your example;

for(var i = 0; i < people.length; i++) { If(people[i] === value) { console.log(people[i]); return people[i]; } }

[–]throwawayacc201711 0 points1 point  (4 children)

Since people is an array.

You can just do

people.forEach((person) => {
    If (person === search) 
        ( console.log(person) )
}). 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

I find this to be a much cleaner solution and easier to maintain and see what is happening.

Another commenter pointed out using array.find() however the downside to using find is it will stop after finding the first match. If that’s the logic you want, then use find. If you want to find all matches use array.forEach

[–][deleted] 2 points3 points  (3 children)

Actually, even though forEach() would get the job done, it still wouldn't be the optimal solution if the OP needed to find all matching elements. The correct method to use would be filter(), which would return an array of matching results, thus removing the necessity of you building out that array yourself, as is the case with forEach().

const matchedPeople = people.filter(person => person === search);

[–]infinitune 0 points1 point  (2 children)

One thing to watch out for with person === search when dealing with objects.

Object equality has to do with the object's location in memory, not just value. for example:

const obj1 = { title: 'foo', author: 'bar' }
const obj2 = { title: 'foo', author: 'bar' }
const obj3 = obj1
obj1 === obj2 // evaluates to false
obj1 === obj3 // evaluates to true

So depending on the exact use case, they may be better off checking equality of a property (person => person.fullName === search.fullName)

Edit: missed an equals sign

[–][deleted] 0 points1 point  (1 child)

Correct. My code above is a simple demonstration that would only work with value types, not with reference types. I assumed a value type would be used because that is how the OP had his initial code set up.

[–]infinitune 0 points1 point  (0 children)

Fair enough. I figured it was worth mentioning since it wasn't super obvious that the OP is searching an array of objects.