0

I am working on a project of mine where I have this contact list contacts which is an array containing objects.

The problem is that my function searchPerson always returns the response for the condition of the searched for person not existing. As soon as I remove the condition and call the function again it returns what was searched for.

I don't understand why with the condition it always return no such person found! when that person exists in the contact list! Can anyone help me understand why this is happening?

This is my code.

var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "[email protected]"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "[email protected]"
};

//Here we populate ou array.
var contacts = [bob, mary];

function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
}


function searchPerson (lastName) {
    var contactsLength = contacts.length;
    for(var i = 0; i < contactsLength; i++){
      //set a condition that we only retrieve the last name if it already exists in out contact list
        if(lastName !== contacts[i].lastName){
            return console.log("No such person found!");
        } else {
            printPerson(contacts[i]);
        }
    }
}
1
  • @RobG IMHO, JS would be a better language without the coercing == operator. Commented Aug 9, 2014 at 23:06

2 Answers 2

2

You're enumerating the entire array, but return "No such person found" as soon as any non-matching person is found. Since the two last names are not the same, you'll always trigger that return line.

Consider using Array.prototype.filter instead to find matching entries:

function searchPerson(lastName) {
    var matches = contacts.filter(function(contact) {
        return contact.lastName === lastName;
    });

    if (matches.length) {
        matches.forEach(printPerson);
    } else {
        console.log("No such person found!");
    }
}

NB: .filter and .forEach are ES5 functions (IE9+ only AFAICR). Use a "shim" to add them to your browser if required.

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

4 Comments

filter is not short-circuiting however, so it's not very efficient, but it shouldn't matter for a few records.
@plalx indeed - I considered that - a mere existence test would be faster with Array.prototype.any, but that doesn't also print the match, it just proves its existence. You could put the call to printPerson inside the .any function's callback, but that's slightly messy. In any event, the OP's code appears intended to print every match, so short circuiting wouldn't be required.
@plalx yes - .some, not .any ! (too many languages in my head!)
@Alnitak Thanks! I understand now! Once you explained the problem I simply replaced console.log("No such person found"); with continue; and it worked too.
0

You need to fix the logic so that for each match found, print the name. If no matches are found, return an error.

function searchPerson (lastName) {
    var contactsLength = contacts.length;

    // Remember if a match is found
    var matchFound = false;

    for (var i = 0; i < contactsLength; i++) {

        // Print each match
        if (lastName == contacts[i].lastName) {
            printPerson(contacts[i]);
            matchFound = true;
        }
    }

    // If no match found, return error message
    if (!matchFound) {
        console.log('Person ' + lastName + ' not found!');
    }
}

2 Comments

@Alnitak—you're welcome to that opinion. To me, the plain JS solution is simpler and hugely faster—about 10 times—and doesn't require shims or special consideration for any browser in use.
ES5 is plain JS! You're correct though that the function call overhead can be a little high. It would be interesting to see how that changes with a much larger array.

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.