Tips for enhancing filtering functionality in ReactJS

Is there a way to create a filter that will only display matching elements when the letters in first_name and last_name strictly match the beginning of the names?

const filterContacts = ({first_name, last_name}) => {
    return first_name.toLocaleLowerCase().indexOf(searchValue.toLocaleLowerCase()) !== -1 
    || last_name.toLocaleLowerCase().indexOf(searchValue.toLocaleLowerCase()) !== -1;
  }

I want the filter to show only exact matches like this: https://i.stack.imgur.com/lTOin.png

If you can help me achieve this, I would greatly appreciate it.

Answer №1

Utilize the String.prototype.startsWith method in JavaScript to determine if a string begins with a specific prefix.

const filterContacts = ({ first_name, last_name }) => {
  const prefix = searchValue.toLocaleLowerCase()

  return (
    first_name.toLocaleLowerCase().startsWith(prefix) ||
    last_name.toLocaleLowerCase().startsWith(prefix)
  )
}

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

Efficient method to retrieve my app's version in a React Native environment

I have a React Native app that I created using the command react-native init. I want to define a global constant for my APP_VERSION so that I can access it in the Authentication/Login screen. Currently, the only place I see this variable is in my package. ...

Creating a Modal using Typescript with NextJS

Currently, I'm working on creating a modal within my app using NextJS with Typescript. Unfortunately, I've been struggling to eliminate the warning associated with my modal selector. Can someone provide guidance on how to properly type this? cons ...

Bringing in a variable from a component that is dynamically imported

I have a dynamically imported (Map) component on my page. const Map = dynamic(() => import('../components/Mapcomp'), { ssr: false, }) In addition to the component, I also need to import a variable from it. const [taskImg, setTaskImg] = useS ...

What is the best way to delay JavaScript execution until after React has finished rendering?

Perhaps this is not the exact question you were expecting, but it did catch your attention :) The issue at hand revolves around the fact that most of the translations in my text do not update when the global language changes. Specifically, the translation ...

The issue of not displaying the Favicon in Next.js is a common problem

I am currently using Next.js version 13.4.7 with the App directory and I am facing an issue with displaying the favicon. Even though the favicon image is located in the public folder and in jpg format, it is not being displayed on the webpage. However, w ...

Error message: "Issue with exporting withRouter and withStyles in React"

Using react in combination with redux and material-ui, I am working on creating a component. Specifically, I am trying to write an export statement export default connect()(withRouter(FirstPage))(withStyles(styles)(FirstPage)) However, I have encountered ...

Upon launching a fresh project with Next.js 13, three errors are immediately encountered

Working with a technology in beta for the first time is throwing some errors my way. Should I just overlook them since it's expected, especially considering that I'm new to Next.js? To kick off my app development, I used npx create-next-app@late ...

What will happen if I have multiple nested SWRConfig components with different options selected?

I am currently utilizing SWRConfig to implement a global fetcher, but I also have the requirement to override this fetcher in certain components. In such a scenario, would the options specified at a higher level of SWRConfig be applied? <SWRConfig ...

"Unable to execute validateOptions as it is not a recognized function

ERROR src/pages/trade/trade-sagas/trade-sagas.unit.test.js ● Test suite failed to run Cannot locate module 'axios' from 'src/pages/trade/trade-sagas/trade-sagas.unit.test.js' 1 | import { runSaga } from "redux-saga"; &g ...

The data list is failing to retain previous elements as new ones are incorporated

I have a list for uploads, and whenever I upload new data, the old data in the list gets removed. However, I want to display all the data together. How can I resolve this issue? const [fileList, setFileList] = useState<AddedFile[]>([]); const beg ...

What could be the reason for encountering a Typescript ts(2345) error while trying to pass a mocked constant to .mockResolvedValue()?

Within my test.tsx file, I have the following code snippet: test('Photos will load', async () => { const mockCuratedPhotos = jest.spyOn(endpoints, 'getCuratedPhotos'); mockCuratedPhotos.mockResolvedValue(mockPhotos); awa ...

The Node is unable to initiate the react index.js file, resulting in an exit with code

Today, I encountered an issue while trying to start my React project. It seems like npm is unable to locate my index.js file, even though it was working perfectly fine yesterday. I have already cleared the npm cache and reinstalled the node modules. The co ...

How can I ensure that every dependency in my package.json is updated to the newest version using Yarn?

My current react app is using deprecated dependencies and in order to get it functional, I need to update these dependencies to more recent (yet stable) versions. According to a discussion on Stack Overflow, for updating dependencies in package.json to th ...

The Fetch API encounters an error when attempting to load > Safari and Firefox from Cloudinary

Currently dealing with an issue that seems to persist even after enabling CORS on my front-end (React.js). The problem only occurs on Firefox and Safari, and I suspect it may be related to the use of Cloudinary, the service responsible for hosting images o ...

An open port could not be located on the x86_64-conda_cos6-linux-gnu system

Recently delved into learning React and encountered some challenges that I could use assistance with. I am in the midst of developing an application using this code snippet: npx create-react-app project-name Upon creating the application, I ran into issue ...

Utilize the get method to showcase data in a material UI table for a React application

Just starting out with React. Managed to create a table component with hard-coded data. However, I now have all the data stored in table.json. Can someone guide me on how to fetch values from table.json using an axios get request an ...

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

Node corrupting images during upload

I've been facing an issue with corrupted images when uploading them via Next.js API routes using Formidable. When submitting a form from my React component, I'm utilizing the following functions: const fileUpload = async (file: File) => ...

React-Select for Creating a Dynamic Multi-Category Dropdown Menu

I am looking to incorporate react-select into my project for a multi-category dropdown list. Specifically, I need the ability to select only one option at most from each category. To better illustrate this requirement, consider the following example wher ...

The error message "writeUserData is not defined" is indicating that there is an undefined variable in the react code

I'm still learning React and I've been working on a new function: This is my code in summary: class Signup extends Component { constructor(props) { super(props); } componentDidMount() { } writeUserData = (userId, username, email) => ...