Exploring an array of objects to find a specific string similar to the one being

I recently developed a TypeScript code snippet that searches for objects in a list by their name and surname, not strictly equal:

list = list.filter(
  x => (x.surname + ' ' + x.name)
          .trim()
          .toLowerCase()
          .search(filter.toLowerCase()) >= 0);

For instance, if I search for "al" and want to find "Alex", the code will display "Alex" as a valid result.

However, when I migrated this code to a JavaScript environment, it encountered errors related to the search function and trim method.

Is there a more efficient way to achieve this functionality without resorting to nested loops?

Answer №1

It seems like your code is in good shape and works well for the scenario you explained, with the exception of outdated browsers that do not support arrow functions.

Another point to note is that when using search, a regex is created from the string provided which could lead to unexpected outcomes if, for instance, a simple period . is passed; in such cases, it might be better to use indexOf.

Below is a demonstration showcasing both methods:

function findUsingSearch(list, filter) {
  return list.filter(
    x => (x.surname + ' ' + x.name)
    .trim()
    .toLowerCase()
    .search(filter.toLowerCase()) >= 0);
}

function findUsingIndexOf(list, filter) {
  return list.filter(
    x => (x.surname + ' ' + x.name)
    .trim()
    .toLowerCase()
    .indexOf(filter.toLowerCase()) >= 0);
}

var data = [{ surname: 'Alex', name: 'Foo' }, { surname: 'Oleg', name: 'Bar' }];

console.log('*** findUsingSearch:')
console.log(findUsingSearch(data, 'al'));
console.log(findUsingSearch(data, 'ol'));
console.log(findUsingSearch(data, 'ul'));
console.log(findUsingSearch(data, '.'));

console.log('*** findUsingIndexOf:')
console.log(findUsingIndexOf(data, 'al'));
console.log(findUsingIndexOf(data, 'ol'));
console.log(findUsingIndexOf(data, 'ul'));
console.log(findUsingIndexOf(data, '.'));

Answer №2

If my interpretation of the question is correct, you are dealing with an array of objects structured like this:

const individuals = [
  { firstName: 'Alice', lastName: 'Jones' },
  { firstName: 'Bob', lastName: 'Smith' },
  { firstName: 'Charlie', lastName: 'Brown' }
];

It seems that you aim to search through this list for a person whose name matches a specific partial string (let's call it partialName)? You can achieve this using the following code snippet:

const result = individuals.find(
  person => {
    const firstName = person.firstName.toLowerCase();
    const lastName = person.lastName.toLowerCase();

    if (`${firstName}${lastName}.includes(partialName.toLowerCase()) {
      return person;
    }
  }
);

This logic can also be condensed into a single line for easier readability:

const result = individuals.find(person => `${person.firstName.toLowerCase()}${person.lastName.toLowerCase()}`.includes(partialName.toLowerCase()));

If you prefer to get an array containing all matching results, simply replace find with filter:

const result = individuals.filter(person => `${person.firstName.toLowerCase()}${person.lastName.toLowerCase()}`.includes(partialName.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

Creating balanced numerical values within the range of 0 to 1 using an array

Is there a way to create a set of numbers between 0 and 1 that is proportional to an array of sales with varying sizes? For instance, if the sales values are [1, 80, 2000], would it be possible to generate an array like [0.1, 0.4, 1]? ...

What is the best way to implement Angular translation for multiple values in a typescript file, while also incorporating parameters?

this.snackBar.open( `Only files of size less than ${this.fileSizeAllowed}KB are allowed`, this.translate.instant('USER_REG.close'), { panelClass: 'errorSnackbar', ...

An effective method for converting a string into a two-dimensional array using JavaScript

One challenge I am facing is checking from a string if a specific fruit has the correct amount on a given date. I've managed to achieve this by converting the string into a 2D array and iterating over the columns. While this method works, I can't ...

Creating a Runescape Tracker: What essentials should I include?

Hello everyone, I am a beginner in the world of programming and I am excited to learn. I have heard that the best way to learn is by working on a project. I have always been interested in creating a Skill Tracker for my clan. Can you offer any advice on wh ...

Methods for dynamically altering the background color of a parent component from a child component

Currently, I am working on a T-shirt design application using fabric.js within reactjs. I have encountered an issue when attempting to change the color of the t-shirt. My goal is to allow the color of the T-shirt to be changed from the child component but ...

What is the best way to incorporate lottiefiles for a loading animation on a Next.js project's landing

Is there a way to incorporate the use of lottie in a Next.js project (App Structure) in order to load an animated logo seamlessly? I attempted to include "use client" without success, and also tried importing Lottie from react-lottie as a dynamic import. ...

Having difficulty locating the correct TypeScript interface for executing GraphQL queries in a React application using Apollo Client

In this React component code snippet, a table is returned with each row containing data fetched from a backend API using GraphQL. While the data is successfully fetched, there seems to be an issue in defining the correct interface for handling the data ret ...

Tips for dynamically loading a modal

Hello, I am curious about dynamically loading modals on different images within my current webpage. For example, when the life of Pi image is clicked, a modal pops up displaying relevant information. I would like this functionality to extend to other ima ...

Incremental migration to Next.js within the current React application

I'm on a quest to uncover practical examples demonstrating the process of gradually transitioning an existing React application towards Next.js. Despite delving into all available Next.js documentation on incremental adoption strategies like subpaths, ...

Issue with jQuery.off when using a dynamic function name

I am currently implementing a modular pattern for writing my JavaScript code and it has been an enjoyable experience! However, I have encountered a challenging situation. My Namespace structure looks like this: var settings, handlers, objects, Namespace ...

redux - managing asynchronous storage using key-value pairs

Utilizing associative arrays with redux and storing them in async storage for later retrieval is my current challenge. When using redux, I am able to quickly access the values and efficiently map the content into cards in my react native app. However, aft ...

Is TypeScript the new replacement for Angular?

After completing a comprehensive tutorial on Angular 1.x, I decided to explore Angular 2 on angular.io. However, upon browsing the site, I noticed references to Typescript, Javascript, and Dart. This left me wondering if my knowledge of Angular 1.x is now ...

Problem with image title in jQuery mobile

My code seems to be having an issue where the title does not display completely when hovering over it. For example, if the title is set as "The Value", only "The" is shown and not "The Value". Can anyone help me identify the mistake? Thank you in advance ...

JavaScript - Implementing dependency injection with promises

I am facing a challenge in passing an object around in JavaScript, with some jQuery involved. :) My goal is to execute the FlappyBarHelper.getUserPropertyCount() method once the promise.success function has completed. I attempted to pass this.FlappyBarHel ...

How can you select a variable using Jquery?

$.get('sampleurl.com',function(result){ target = $(result #specificID).attr("href") // Can someone help me with this??? }) I fetch content from an external website using $.get and store it in the result variable, now I'm trying to figure ou ...

Issue with Enter key not working on an individual textbox within Javascript/PHP chat functionality

Recently, I created a chat feature with text boxes that send messages when the ENTER key is pressed. However, I encountered an issue with it not working for the "Warning" functionality. Whenever I press Enter in this context, nothing happens. Can anyone pr ...

How can I implement a redirect back to the previous query page post-authentication in Next.js 13?

To enhance security, whenever a user tries to access a protected route, I plan to automatically redirect them to the login page. Once they successfully log in, they will be redirected back to the original protected route they were trying to access. When w ...

What could be causing NPM to generate an HTTP Error 400 when trying to publish a package?

My current goal is to release an NPM package named 2680. At the moment, there is no existing package, user, or organization with this specific name. Upon inspection of my package.json, it appears that everything else is in order. Here are all the relevant ...

Perform a single click and a double click on an anchor element in the document

I am attempting to implement two actions when a user clicks on an anchor tag. The anchor tag will contain a video link. My goal is for the URL to open in a new window when the user single-clicks on the anchor tag, and for the use of the HTML5 download attr ...

There seems to be a problem as exits.success is not a recognized function -

Currently, I am exploring how to utilize Sails.js with the node-machine-syntax specifically in the context of listing flights. The code snippet below outlines my attempt at achieving this: /** * FlightsController * * @description :: Server-side actions fo ...