1

/*please have a look at the following function. Its a simple function. I want to iterate over the movies array and return the element; only if the element's title is exactly same as the argument passed in. otherwise return false at the end of the iteration.
The problem is, it always return false. However, if I use a regular forloop instead of forEach loop, it works perfectly fine.. can someone please explain why is this situation?????? Thank You in advance. */

function searchMovies(title) { movies.forEach(function(ele){ if(ele.title === title){ return ele; } }); return false; } //movies array var movies = [ {title: 'The Hobbit'}, {title: 'The Great Gatsby'}, {title: 'Gone with the Wind'} ]; //the following line calls the function searchMovies('The Great Gatsby'); 
0

2 Answers 2

3

You're returning from inside the callback passed to forEach which forEach ignores every time and call the callback to the next element. What you need is to use find like this:

function searchMovies(title) { var found = movies.find(function(ele){ return ele.title === title; }); return found; // found will be either and item from the array (if find found something) or undefined (if it doesn't) } 

Note 1: the movies array should be either defined before the function searchMovies, or passed to it as a parameter (the best approach).

Note 2: if you want to return an array of all the matched element (if there is duplicates in the array and you want to return all of them), then use filter, which is used the same way and it return an array of all the matched elements (an empty one if nothing matched).

Sign up to request clarification or add additional context in comments.

Comments

1

Because you're returning inside the forEach function.

function searchMovies(title) { var foundMovie = false; movies.forEach(function(ele) { if (ele.title === title) { foundMovie = ele; } }); return foundMovie; } 

3 Comments

Note, this will find the last match instead of the first which may not be desired
@Phil and will loop through the whole array even if the found element was in the first index!!
@Phil and ibrahim, you're correct. I was just showing them how to get it work using the forEach they tried :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.