0
let teams = [
{ name : 'Patriots' },
{ name : 'Dolphins' },
{ name : 'Jets' }, 
{ name : 'Bills' }
]

let search = (name) => {
    for( let i = 0; i < teams.length; i++ ) {
        if( name === teams[i].name ) {
            return teams[i];
        }
        return false;
    }
}
console.log(search('Patriots')); // returns { name : 'Patriots }
console.log(search('Dolphins')); // return false

I am trying to write a search function to search an array of objects. When I search for the first object it returns it. When I search for any other object in the array it return false. Is there a way to have the for loop run completely before moving onto my if else statements or is there a better way to do this?

3
  • 3
    Put the "return false" outside the for loop Commented Jul 18, 2017 at 15:47
  • wow... thanks @AlexBieg Commented Jul 18, 2017 at 15:48
  • Haha no worries. It happens to the best of us. Commented Jul 18, 2017 at 15:49

2 Answers 2

3

You need to remove 'return false' from within the for loop, this is triggering after the loop has gone through the first value so it is never reaching 2,3,4th property/teams.

let teams = [
    { name : 'Patriots' },
    { name : 'Dolphins' },
    { name : 'Jets' }, 
    { name : 'Bills' }
]

let search = (name) => {
    for( let i = 0; i < teams.length; i++ ) {
        if( name === teams[i].name ) {
            return teams[i];
        }
    }
    // return 'false' if not found
    return false
}
console.log(search('Patriots')); // returns { name : 'Patriots }
console.log(search('Dolphins')); // returns { name : 'Dolphins }
console.log(search('Oranges'));  // returns false

return teams[i]; will stop the loop from continuing once it has found a matching value.

I've added return false after the for loop, so If the team name is not found the function will return 'false'.

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

2 Comments

+1 but if the expectation is for it to return false if not found then you need to add return false after the for loop. That way the search either returns the result, or it iterates over the array and then returns false. I'd also suggest using developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
Thanks for pointing that out Liam, ive updated answer to include this scenario.
1

You can do it with filter and reduce.

const teams = [
    { name : 'Patriots' },
    { name : 'Dolphins' },
    { name : 'Jets' }, 
    { name : 'Bills' }
]
const search = (arr, s) => arr.filter(({name}) => name === s).reduce((p,{name}) => name || p, false) 

console.log(search(teams, 'Patriots'))

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.