Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

89
Views
How to filter array of object depends on input onChange text (React)

(React Problem)

Let's say we have array of objects like this:

    const books = [
      {
        author: "Marcel Proust",
        title: "In Search of Lost Time",
        pageNumber: 123,
      },
      {
        author: "James Joyce",
        title: "Ulysses",
        pageNumber: 123,
      },
      {
        author: "Miguel de Cervantes",
        title: "Quixote",
        pageNumber: 123,
      },
      {
        author: "Herman Melville",
        title: "Moby Dick",
        pageNumber: 123,
      },
      {
        author: "William Shakespeare",
        title: "Hamlet",
        pageNumber: 123,
      },
    ];

Also we have an input and state like this:

    const [text, setText] = useState("");

    const handleOnChange = (event) => {
      setText(event.target.value);
    };

    <input value={text} onChange={handleOnChange} />;

Now, I would like to filter this array depends on input text, and [author | title] property.

Example:

If user types 'M', the array of object should look like this:

    const books = [
      {
        author: "Marcel Proust",
        title: "In Search of Lost Time",
        pageNumber: 123,
      },
      {
        author: "Miguel de Cervantes",
        title: "Quixote",
        pageNumber: 123,
      },
      {
        author: "Herman Melville",
        title: "Moby Dick",
        pageNumber: 123,
      },
    ];

...because the author or title start with letter M.

7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

Try the following:

const filteredBooks = books.filter(book => {
  return book.title[0] === text || book.author[0] === text;
})
7 months ago · Juan Pablo Isaza Report

0

You should use a filter on your books array.

const filtered = books.filter(({author, title}) => author.includes(text) || title.includes(text)

This will filter with your text in ANY position on author or title. So in your example, if you type "S", you will have "William Shakespeare". If you want to search only from the begining, you can use startsWith instead of includes

7 months ago · Juan Pablo Isaza Report

0

Try this filter function:

books.filter(({
  author,
  title
}) => author.toLowerCase().includes(text.toLowerCase()) || title.toLowerCase().includes(text.toLowerCase()))
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.