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

Embracing Typescript promises over jQuery deferred for improved code efficiency and reliability

Currently, I have the following lines of code that utilize the JQueryDeferred object from the type definition class jquery.d.ts. My goal is to replace jQuery deferred with TypeScript promises. Here is the existing JQueryDeferred code: class A { privat ...

Adding connected types to a list using Typescript

Question regarding Typescript fundamentals. In my code, I have a list that combines two types using the & operator. Here is how it's initialized: let objects: (Object & number)[] = []; I'm unsure how to add values to this list. I attem ...

Tips for updating the pagination layout in Material UI Table

Currently, I am attempting to modify the background color of the list that displays the number of rows in MUI TablePagination. <TablePagination style={{ color: "#b5b8c4", fontSize: "14px" }} classes={{selectIcon: ...

Tips for accessing the firebase user's getIdToken method in Next.js after a page reload

Currently, I am developing a Next.js project and implementing user authentication using Firebase's signInWithPhoneNumber method for phone number verification. After successful verification, I receive a Firebase user with the getIdToken method to retri ...

Verification of the data entered in the input box

I am looking to develop an Input Box where users can enter the private details of a person. The first character must be either A or E, and the rest can be alphanumeric with no special characters allowed. I need to implement validation on the client side to ...

Tips for maintaining type information when using generics in constructors

class Registry<Inst, Ctor extends new (...args: unknown[]) => Inst, T extends Readonly<Record<string, Ctor>>> { constructor(public records: T) { } getCtor<K extends keyof T>(key: K) { return this.records[key] } getIns ...

What could be causing FormArrayName to consistently display as undefined in my HTML code, even when the safe-navigation operator is employed

Currently, I'm referring to the Angular Material example found at https://angular.io/api/forms/FormArrayName Upon initializing the packageForm formGroup in ngOnInit() and logging it in the console during ngAfterViewInit(), I can see that the translat ...

Adjusting and arranging multiple thumbnail images within a container of specific width and height

I need a user-friendly method to achieve the following. The thumbnails will not be cropped, but their container will maintain a consistent height and width. The goal is for larger images to scale down responsively within the container, while smaller image ...

What is the best method for sharing templates and logic in VUE?

Two separate components with shared logic and template, making it appear as though one is extending the other. Think of Drop and Pick components in this manner: // pick.js import Vue from 'vue' import Component from 'vue-class-component& ...

Remove the bottom border from the active tab by utilizing the <div> and <a> elements

I am facing an issue with a tabbed menu on my webpage. While the menu is functioning correctly, I am struggling to remove the bottom border from the active tab. You can view all of my test code here. While I have come across solutions using <ul> an ...

Exploring modules alias functionality in TypeScript

Initially, I believed that using path & basePath in tsconfig would allow aliases, but it appears not to be the case. "moduleResolution": "node", "baseUrl": "./src", "paths": { "@api/*": [&qu ...

turning off next.js server side rendering in order to avoid potential window is undefined issues

I am currently managing a private NPM package that is utilized in my Next.js project, both of which are React and Typescript based. Recently, I integrated a graph feature into the NPM package and encountered an issue where any reference to window within t ...

creating a Vue app using Node results in an HTML page with no content due to syntax errors

After creating a VueJs page using the CLI, I wanted to share it with others who might not have Vue CLI or Node installed. Just like opening .html files in a browser, I tried to open the index.html file after building it. However, when I opened the file, a ...

I'm curious about how to implement textarea functionality within Angular for modeling purposes

I have a desire to utilize the model and transmit it to the server. One instance of this is sending comments. comment.model.ts export interface Comment { article_no: number; username: string; nickname: string; creatat: Date; content: string; } ...

Put a watch on a variable as soon as it is set

When initializing a variable, I want to use the $watch function in Angular without it automatically initializing right away. Is there a way to accomplish this? $watch $scope.$watch(function () { return $scope.character.level; }, function (ne ...

What is the best way to showcase a table below a form containing multiple inputs using JavaScript?

Context: The form I have contains various input fields. Upon pressing the [verify] button, only the "first name" is displayed. My goal is to display all input fields, whether empty or filled, in a table format similar to that of the form. Exploration: ...

What is the best way to handle the resolution of multiple promises as they complete?

Suppose I have three different promises each taking a varying amount of time to resolve - 1000ms, 2000ms, and 3000ms respectively. How can I simultaneously start all the promises and handle them as they get resolved? For instance: let quickPromise = new ...

Unearthing the worth of the closest button that was clicked

I am currently working on a profile management feature where I need to add students to the teacher's database. To achieve this, I am using jQuery and AJAX. However, I am encountering an issue where clicking the "add" button for each student listed on ...

Error occurs in Angular Mat Table when attempting to display the same column twice, resulting in the message "Duplicate column definition name provided" being

What is the most efficient method to display a duplicated column with the same data side by side without altering the JSON or using separate matColumnDef keys? Data: const ELEMENT_DATA: PeriodicElement[] = [ {position: 1, name: 'Hydrogen', wei ...

empty responseText from GET request using AJAX

I've been working on a chatbox using AJAX and I've encountered an issue where my xhttp.responseText is coming back empty. In firebug, I can see that the GET request is being sent and the correct text is being returned, but for some reason it&apos ...