DEV Community

karthikeyan
karthikeyan

Posted on • Edited on

3 1

simple search filter array of objects in javascrit (React js)

we are going to see how to filter the array of object when user type something in input field

first we take some mock data

  const  data = [
  {name:'karthi'},
  {name:'mani'},
  {name:'siva'},
  {name:'raj'}];
Enter fullscreen mode Exit fullscreen mode

add map the data first

{data.map((e)=>(
        <li>{e.name}</li>
      )
Enter fullscreen mode Exit fullscreen mode

after that we need to add filter function

{data.filter((e)=>e.name.toLowerCase().includes(searchtext.toLowerCase())).map((e)=>(
        <li>{e.name}</li>
      )
Enter fullscreen mode Exit fullscreen mode

so we have filter function now after that we need to get the user input text so we can use either usestate or useref here i am using usestate

 const handleinput = (e) => {
    console.log(e.target.value)
    setsearchtext(e.target.value)
  }
Enter fullscreen mode Exit fullscreen mode

thats all you got it

Full code :

import { useState } from "react";
import "./styles.css";

export default function App() {
    const  data = [
    {name:'karthi'},
    {name:'mani'},
    {name:'siva'},
    {name:'raj'}];
  const [searchtext, setsearchtext] = useState('');
  const handleinput = (e) => {
    console.log(e.target.value)
    setsearchtext(e.target.value)
  }
  return (
    <div className="App">
      <input
      placeholder="enter"
      onChange={handleinput}
      />
      {data.filter((e)=>e.name.toLowerCase().includes(searchtext.toLowerCase())).map((e)=>(
        <li>{e.name}</li>
      )
        )}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more