Unable to find the expected outcome when searching through an array of objects

I've been tackling a project that involves a contact list called contacts, which is an array filled with objects.

The issue I'm facing is that my function searchPerson consistently returns "No such person found!" even when the searched-for individual exists. Surprisingly, if I remove the condition and rerun the function, it successfully finds the desired entry.

I'm puzzled as to why, with the condition in place, it repeatedly shows "no such person found!" while the person does indeed exist in the contact list! Could someone provide insights into why this unexpected behavior is occurring?

Below is the snippet of the code:

var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f4f9f4b8fcf9f8f3e5d6f3eef7fbe6faf3b8f5f9fb">[email protected]</a>"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f79a96858ed99d989f99849899b7928f969a879b92d994989a">[email protected]</a>"
};

//Here we populate our 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 our contact list
        if(lastName !== contacts[i].lastName){
            return console.log("No such person found!");
        } else {
            printPerson(contacts[i]);
        }
    }
}

Answer №1

You have been looping through the entire array, but as soon as any non-matching person is found, you return "No such person found". This means that since the last names do not match, the return line will always be triggered.

Instead of enumerating the array, consider using Array.prototype.filter 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!");
    }
}

Keep in mind that .filter and .forEach are ES5 functions (compatible with IE9+). You can use a "shim" to add them to your browser if necessary.

Answer №2

To correct the issue, ensure that the name is printed for each match identified. If no matches are discovered, an error message should be returned.

function findPerson (searchName) {
    var totalContacts = contacts.length;

    // Keep track of whether a match was found
    var matchLocated = false;

    for (var j = 0; j < totalContacts; j++) {

        // Display each matching contact
        if (searchName == contacts[j].lastName) {
            displayContact(contacts[j]);
            matchLocated = true;
        }
    }

    // If no match is located, output an error
    if (!matchLocated) {
        console.log('Unable to find person with the last name ' + searchName + '.');
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Counting down the time in Javascript until the next hour

I'm currently having trouble implementing the jQuery Countdown plugin by Keith Wood. My goal is to show the remaining hours, minutes, and seconds until a specific time of day (e.g., 18:00:00). The code within the body tags is as follows: <?php $s ...

Develop objects with a fixed position - three.js

I am currently working on a game utilizing the three.js library and I have a specific requirement. I would like to incorporate a small "panel" on the screen that remains stationary regardless of the user's navigation through the 3D environment. Essent ...

Form_Open will automatically submit - Ajax Submission in CodeIgniter

I am facing an issue with submitting my form via Ajax. Despite setting up a function to prevent the page from refreshing upon submission, it seems like the form still refreshes the page every time I click submit. I even tried creating a test function to lo ...

Modify the color of the chosen option in the dropdown menu without affecting the rest of the options

I am facing an issue with dynamic drop down lists in my HTML content. The requirement is to change the color of the selected option to dark red if the option is "success". I have implemented a jQuery function for this purpose. HTML: <select class="rea ...

What is the best way to display "No results found" in Mat-select-autocomplete?

I am working with the mat-select-autocomplete for a multiselect dropdown. When searching for values that are not in the list, I want to display a message saying "No results found". Can someone please help me achieve this? Link to Code ...

Trouble with Bootstrap modal implementation when using ajax and looping through data

I am having an issue with using the BS modal to display a form containing a select box and updating records in the database via an ajax call. The trigger button to open the modal consists of <i></i> tags with the same class name, itagbtn, and d ...

Error: Selenium-Javascript tests encountering an unexpected token issue

Having worked with Selenium using Java for a long time, I decided to switch gears and start writing Selenium scripts in JavaScript. I found a helpful guide to learn JavaScript with Selenium, which you can check out here. However, when I attempted to run n ...

Leveraging a value from a 'then' block in a function's return statement in Types

Here is a function I have: function configureClient(): ApolloClient<ApolloCache<any>> { let myToken = getOktaToken().then(token => { return token }); return new ApolloClient<InMemoryCache>({ uri: "someUrl" ...

Issue encountered in v-on event handler: "authentication is not a valid function" - Vue.js

I am currently incorporating Firebase into a VueJS project. My API credentials are stored in a file named fb.js import firebase from 'firebase' var firebaseConfig = { apiKey: "*****", authDomain: "*****", proje ...

element with singular border

I overlaid one div on top of another to create a border effect. Check out this example: However, I am facing an issue: when I hover the mouse over the image, only the div with the border gets focus (for instance, for right-clicking and saving the image), ...

Understanding the fundamentals of event handling in JavaScript

Is there a way to access the object that called the event handler within the event handler function itself? For example: marker.on('dragend', onDragEnd); In this case, marker is the object that triggers the ondragEnd function on the Dragend eve ...

Tips for Filling Kendo Dropdown with JSON Data

I'm facing an issue with populating a Kendo dropdown using AJAX JSON response. The dropdown list is showing up blank. Can anyone point out what I might be missing here? Your help would be greatly appreciated. Here's the corresponding HTML code: ...

Creating a structure with a fixed-size character array field in ctypes and how to initialize it

What is the proper way to initialize a fixed-size character array like char a[32] within a structure using ctypes? See below for an example: import ctypes class MyStructure(ctypes.Structure): _fields_ = [("a", ctypes.c_char * 32)] a = (ctypes.c_char ...

Developing a responsive navigation bar for mobile devices

Can anyone help me with creating a mobile navbar that shows the hamburger icon on smaller screens? I would like the links to appear in blocks when the icon is clicked. I attempted to make it using an SVG icon for the hamburger and setting the display to n ...

Do I actually have to reiterate all these requirements in each route module file?

As I work on developing a more extensive web application, I have come to realize the importance of modularizing my routes into separate files. However, in doing so, I've noticed that I end up duplicating a lot of required modules. Prior to moving the ...

Printing only the last element of a Swift array

This is my class. class dictionaryWord Object { @objc dynamic var word: String? @objc dynamic var Defination: String? @objc dynamic var dateCreated: Date? } The goal is to split the Definition by commas to display each part on a new line. W ...

Exploring the functionality of Angular directives for bidirectional data binding with object references

In my custom Angular directive (v1.4.3), I am passing two bindings. The first binding is an Object with 2-way binding (model: '=') that can either be an Array or a single Object like [{something: 'foo'}, {something: 'moo'}, ...

Unable to retrieve responseText from AJAX call using XrayWrapper

I am utilizing the IUI framework and attempting to retrieve the results from an ajax call. When inspecting the call in Firebug, it shows an "XrayWrapper[Object XMLHttpRequest{}", but I am struggling to access the responseText from the object. Upon expand ...

Statement consistently returning true

I need assistance in verifying the accuracy of an input and moving on to the next word if it's incorrect. "Apples", "Bananas", "Pears", "Door", "Towel", "Computer", ]; var x = myArray[Math.floor(Math.random()*myArray.length)]; function clearbox(){ ...

Navigating through JSON data structures

Can anyone assist me with looping over an object that contains array values? I've been struggling with this for some time. My knowledge of JSON data structures is limited. var storeProducts = {"items": [ { "imgsrc": "https://cdn.shopify.com/s/fil ...