Implement a condition within a Javascript filter operation

I am trying to filter users based on their first name and/or last name, but I keep encountering the error:

TypeError: Cannot read property 'toLowerCase' of undefined

const users = [{name: 'john', lastname: "doe"}, {name: 'mary'}]

let searchName = "jo"
let searchLastName = ""

users.filter((user) =>
    user.name
        .toLowerCase()
        .includes(searchName.toLowerCase())

    && (user.lastname // Check if user has a last name before proceeding
        ? user.lastname
            .toLowerCase()
            .includes(searchLastName.toLowerCase())
        : true // If no last name, consider it as a match
)

How can I modify the filter function to only check for last name if the user actually has a last name (I know they always have a first name)?

Answer №1

Option A: lastName is checked only if it is provided:

users.filter((user) =>
    user.name
        .toLowerCase()
        .includes(searchName.toLowerCase())

    && (
        !user.lastname
        || user.lastname
            .toLowerCase()
            .includes(searchLastName.toLowerCase())
    )
)

Option B: an extra condition that states lastName must be provided:

users.filter((user) =>
    user.name
        .toLowerCase()
        .includes(searchName.toLowerCase())

    && user.lastname
    && user.lastname
        .toLowerCase()
        .includes(searchLastName.toLowerCase())
    )
)

Answer №2

One way to ensure the variable exists is by utilizing JavaScript's automatic boolean coercion:

&& person.lastName   // This will evaluate to false if it is empty, null, or undefined
&& person.lastName
    .toLowerCase()
    .includes(searchLastName.toLowerCase())

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

Tips for handling ng-if during element presence checks

There's a hidden div on my web page that is controlled by an ng-if directive. I'm looking to create a test that confirms the presence of the element only when it should be visible. If the condition set by ng-if is not met, the element is complete ...

Attempting to alter the animations depending on the color button that has been selected

Bootstrap radio buttons are being utilized. I want the animation to change when one of these buttons is selected. I am currently working on changing colors in JavaScript. I attempted to use a for each loop but encountered errors stating that it is not a ...

Struggling with configuring AngularJS?

I've been working on a simple setup, but I can't figure out why AngularJS isn't displaying the content within the curly brackets. It's got me completely baffled. If you'd like to check it out, here's the link to the plunker: ...

Interactive form created with asp.net and dynamic javascript functionality

Hello, I am a beginner in web development. I have created an application that includes a button. When the button is clicked, a popup window should appear with 2 fields and another button. Once the user clicks the button in the popup window, the data ente ...

The "read more" button seems to be malfunctioning

I've been working on integrating a gallery of images into my posts. My goal is to display 4 images initially, followed by a "load more" button that, when clicked, will reveal another set of 4 images, and so on. I have already created the HTML, CSS, an ...

GoogleMaps v3 domListener not triggering in Angularjs directive when using Phonegap

I have a directive in one of my templates and here is the code for that directive: appDirectives.directive('map', function() { return { restrict: 'E', scope: { onCreate: '&' }, link: function ($sco ...

Using Vue to implement a "v-model" on a custom component that incorporates the ace-editor

Snippet CustomEditor.vue: <template> <div class="custom-container"> <div class="custom-editor" ref="editor"></div> </div> </template> <script> import ace from 'ace-builds' import 'ace- ...

Achieve the effect of making the Bootstrap JS Collapse text bold after it has been

Is there a way to make Bootstrap JS Collapse text Bold after it has been clicked on? <tr data-toggle="collapse" data-target="#demo8" class="accordion-toggle"> <td> <div class="fa ...

What could be causing the regex to fail when trying to validate the header in a request?

Utilizing regex to enhance the response header, I am referring to this set of instructions: https://nextjs.org/docs/api-reference/next.config.js/headers The documentation explains how to incorporate Regex Path Matching, however, it seems to be ineffectiv ...

javascript exchange the content when clicking on a hyperlink

I'm encountering a bit of a challenge with this task... My javascript skills are a bit rusty, and I can't seem to pinpoint what's going wrong. My goal is to have a navbar that disappears when a user clicks on a small arrow, revealing a seco ...

Tips for optimizing the rendering of a mesh multiple times in three.js

Currently, I am in the process of developing a cube world game. This involves working with a 3D array of blocks, where each block is represented by an array of mesh (although at this stage, the mesh array simply consists of a single mesh resembling a cube) ...

When it comes to using the text() function, the statement encounters difficulty

let person = $(".tekst").text(); if (person=="XxX") { $("#discu").css("display", "none"); } alert(person); When I access my element with class .tekst and get its text using the text() function, it correctly displays as XxX, which is what I expected. ...

Struggling to grasp the concept of nested scope within AngularJs

I found myself puzzled while reading an article on this particular website (pitfall #5): My query is: Does this situation resemble having two variables with the same name in plain JavaScript, where one is locally defined (e.g. within a nested function ...

Comparing AngularJS and Node JS in serving web pages, which is better?

Currently, I'm in the process of learning how to develop a web using angular and node JS. One aspect that I am struggling with is determining where to acquire the URLs for links. After doing some research on stack overflow and various tutorials relate ...

How can I locate and modify a particular cell within an HTML table using just JavaScript?

For my project, I am required to develop a functional shopping cart with a remove function. If an item is already in the cart, it should update the existing data when added again. Let's say I have the following items in my cart: Name: Quantity: Pric ...

What's causing this script to malfunction on Safari and Chrome?

My code works perfectly on Firefox, but I'm having issues with my "calc" variable in Chrome and Safari. You can view the problem here: Any assistance would be greatly appreciated! var hidetop = $("#hidetop"); var range = $("#hidetop").height ...

Monitoring the accumulation of a running sum with JavaScript

In my JavaScript function, I am attempting to maintain a running total that updates every time the user interacts with the button on the screen. Essentially, each click should contribute to the accumulating sum. ...

An unexpected issue occurred during runtime, specifically a TypeError stating that the function posts.map is not

Currently, I am diving into the world of nextjs and decided to follow a tutorial on building a Reddit clone that I stumbled upon on Youtube. However, I encountered a persistent issue: posts.map is not a function I would appreciate any assistance you can o ...

Exploring the JavaScript Bitwise NOT Operator and the toString() Method

Greetings to all in advance! alert((~1).toString(2)); As a result, the output is: -10 However, in PHP/Java, it produces 11111111111111111111111111111110 I'm puzzled. What could be causing Javascript to include a "-" at the start of the output? ...

Effortlessly transfer files with Ajax through Box

I attempted to utilize the Box.com API for file uploads according to instructions from https://gist.github.com/seanrose/5570650. However, I encountered the following error message: `XMLHttpRequest cannot load "". No 'Access-Control-Allow-Origin&ap ...