Tips on sorting ID strings that include a specific substring

I have a user input that may include a street, postal code, city, or a combination of them. How can I filter an array of objects to find those that contain any of these strings in the corresponding fields?

getFilteredCentersSuggestions(searchTerm: string) {
    searchTerm = searchTerm.toLowerCase();
    return this.centersList.filter((center) => center.city.toLowerCase().includes(searchTerm) || center.postalCode.toLowerCase().includes(searchTerm) || center.street.toLowerCase().includes(searchTerm));
  }

The current code works well for single terms, but when entering multiple terms like "city postalCode", it fails to return the desired results...

Is there a way to directly filter the object fields or do I need to split the input and apply additional filtering within the existing filter?

Example:

Array:

[
  {
    id: "1",
    city: "city1",
    street: "street1",
    postalCode: "postalCode1"
  },
  {
    id: "2",
    city: "city1",
    street: "street2",
    postalCode: "postalCode2"
  },
  {
    id: "3",
    city: "city2",
    street: "street3",
    postalCode: "postalCode3"
  },
]

Input 1: "city1 postalCode1"

Expected result 1: Object with id == 1


Input 2: "city1"

Expected result 1: Objects with id == 1 && id == 2

Answer №1

fetchCenterSuggestionsBasedOnFilters(filterString: string) {
  const filters = filterString.toLowerCase().split(' ')
  return this.centerList.filter(center=>filters.every(filter=>
    [center.city, center.postalCode, center.province].some(field=>field.toLowerCase().includes(filter))))
}

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

Rearrange the layout by dragging and dropping images to switch their places

I've been working on implementing a photo uploader that requires the order of photos to be maintained. In order to achieve this, I have attempted to incorporate a drag and drop feature to swap their positions. However, I am encountering an issue where ...

What is the best way to invoke a Javascript function within the same file using PHP?

I am facing an issue with my PHP file named "PhpCallJavascript". I am attempting to call the function CreateSVG() from within the PHP code. However, it seems that it is not working. Do I need to incorporate AJAX here? Or perhaps there is another solutio ...

The Node.js engine isn't updating to support compatibility with Firebase functions

Encountered First Failure Below is the content of package.json "engines": { "node": "8.0.0" }, Error: The engines field in the functions directory's package.json is unsupported. You can choose from: {&quo ...

Tailwind Component Grid in Action

I'm trying to arrange a list of JavaScript components in a grid with one row and twelve columns. I want to use only six columns for the actual elements, while having three columns of padding on each side of the grid. My goal is to place three elements ...

What is the best way to retrieve the current state from a different component?

My goal is to access a user set in another component. I passed the state from the highest component (which is the app) by utilizing this function for state change. handleRegisterSubmit(e, username, password) { e.preventDefault(); axios.post('/au ...

Using React and Material UI to create a table filtering system with checkboxes

I'm currently developing a filtering feature using checkboxes for a data display in a project utilizing React and Material-UI. Is there a custom solution available within Material-UI? If not, what steps should I take to achieve this? As I am rel ...

Create a stunning MUI App bar with a blurred effect below a fixed Navbar

Is there a method to apply a blur effect to the background of my material-ui AppBar component, creating a visually appealing overlay below the fixed navbar? I have experimented with using filter: blur(0) but it does not achieve the desired result. I am lo ...

What is the best way to receive a single response for various API endpoints?

I need to retrieve a single response from an API that has multiple page URLs. How can I accomplish this with just one API call? Here is my code: async function fetchArray () { // Fetch `urlArray` from object parameter let urlArray = []; ...

top margin is functioning properly in Internet Explorer, but not in Google Chrome

margin-top is behaving differently in IE compared to Google Chrome. Two menus are supposed to be displayed one above the other in my design. The issue lies in the line margin-top:30%; within .anothermenu ul. In Chrome, the second menu appears above the f ...

What are the steps to update content by referencing an id in the hash URL?

Currently, I am utilizing the following code snippet to extract an ID from the hash URL: var integer = window.location.hash.match(/\d+/) | 0; alert(integer); However, I have encountered an issue where upon using the back button after modifying the U ...

No location matched any routes

I'm currently working on a notes application, and I've encountered an error when trying to edit the notes. The error message says "No routes matched location id ...". Any idea what could be causing this issue? The approach I'm taking is to ...

Blending synchronous and asynchronous testing with Mocha

There is a function that calculates certain values and informs the user about events using callbacks: function returnAndCallback(callback) { callback(5); // not always called return 3; } Incorporating Mocha and Should.js, a test was created: descri ...

Displaying an interactive 2D floorplan in a web browser with the use of html5 and javascript

In the process of updating my old Flash viewer, I am looking to display interactive 2D floorplans exported from AutoCAD. Currently, I convert the AutoCAD files into XML files containing the X and Y coordinates of the various elements on the floorplan such ...

"Encountering HTTP 400 Bad Request Error When Using Flask and Ajax for Post Requests

I'm currently developing a small Flask-based website and I want to use Ajax to send data from the client to the server. So far, I've only used Ajax requests to fetch data from the server, but this time I want to submit data via a POST request. O ...

Encountering the "Headers have already been sent" error in NodeJS

I recently started working with node and I'm in the process of developing a rest node API. I've implemented Express for HTTP and JWT for authentication. However, when I make a request to /node/me with the header 'x-auth', I encounter th ...

Can Comet be implemented without utilizing PrototypeJs?

Can Comet be implemented without utilizing PrototypeJs? ...

Learn how to display only certain elements when triggered by the click of another

I have developed a tab system where each tab contains a unique set of questions and answers. The structure of the tabs is exactly as I envisioned, but I am facing challenges with toggling the display of answers when their respective questions are clicked. ...

Using jQuery to add emoticons to a div element

I am currently developing a small chat application and I would like to incorporate emojis into it. My goal is to allow users to click on an emoji, which will then appear in the text area where they type their message. When a user clicks on "select," I want ...

Numerous linkages facilitated by node-mongodb-native

Currently, I am working on a function aimed at inserting a document into a MongoDb database using the node-mongodb-native module. The function works perfectly fine, except when multiple documents are inserted back-to-back. To test how my function handles m ...

Updating a document using the nano module in CouchDB is not supported

I am currently utilizing the Node.js module known as nano Why is it that I am unable to update my document? I need to set crazy: true and then change it back to false. This is the code I have: var nano = require('nano')('http://localhost ...