3

How to search/filter arrays within arrays in React? For example:

I have this data (videosData.js):

[
    {
        "id": 1,
        "title": "Video 1",
        "video_leght": "00:50:00",
        "date": "20.05.2010",
        "questions": [
            {
                "id": 1,
                "question": "Question 1 ",
                "url": "Link"
              },
              {
                "id": 2,
                "question": "Question 2",
                "url": "Link"
              },
              {
                "id": 3,
                "question": "Question 3",
                "url": "Link"
              }         
        ]
    },
    {
        "id": 2,
        "title": "Video 2",
        "video_leght": "01:00:00",
        "date": "14.07.2016",
        "questions":[
            {
                "id": 1,
                "question": "Question 1 ",
                "url": "Link"
              },
              {
                "id": 2,
                "question": "Question 2",
                "url": "Link"
              },
              {
                "id": 3,
                "question": "Question 3",
                "url": "Link"
              }        
        ]
    }
]

This is my complete code:

import React, { useState } from "react";
import Style from "./SearchResults.module.css";
import DataList from "../data/videosData";

function SearchResults() {
  const [search, setSearch] = useState("");

  return (
    <div className={Style.Body}>
      <div className={Style.Search_div}>
        <input
          className={Style.Textbox1}
          onChange={(e) => setSearch(e.target.value)}
        ></input>
        <button className={Style.Btn_Potrazi}>Trazi</button>
      </div>

      <div>
      {DataList.filter((item) => {
            return search.toLowerCase() === ""
              ? ""
              : item.title.toLowerCase().includes(search);
          })
          .map((item) => (
            <h2>{item.title}</h2>
          ))}
      </div>
    </div>
  );
}

export default SearchResults;

I managed to filter the "title" in the array but what I really need is filter out only the questions. So when typing in the search box a word it would filter and show only that question that contains that word...

I'm completely newbie to web development, I watched lots of YouTube videos but just couldn't find a tutorial with an explanation in own words on how to solve this problem.

Thanks in advance!

2 Answers 2

3

UPDATE: Go to this link -> https://codesandbox.io/s/sweet-chaum-39px6u?file=/src/App.js for the example of returning an element within the filtered map.

const questionFilter = [
    {
        "id": 1,
        "title": "Video 1",
        "video_leght": "00:50:00",
        "date": "20.05.2010",
        "questions": [
            {
                "id": 1,
                "question": "Question 1 ",
                "url": "Link"
              },
              {
                "id": 2,
                "question": "Question 2",
                "url": "Link"
              },
              {
                "id": 3,
                "question": "Question 3",
                "url": "Link"
              }         
        ]
    },
    {
        "id": 2,
        "title": "Video 2",
        "video_leght": "01:00:00",
        "date": "14.07.2016",
        "questions":[
            {
                "id": 1,
                "question": "Question 1 ",
                "url": "Link"
              },
              {
                "id": 2,
                "question": "Question 2",
                "url": "Link"
              },
              {
                "id": 3,
                "question": "Question 3",
                "url": "Link"
              }        
        ]
    }
]

const result = questionFilter.map(item => 
    item.questions.filter(qitem => qitem.question.includes('Question 1'))
)

console.log(result)

Here's how it done.

Sign up to request clarification or add additional context in comments.

3 Comments

It works great but only with console.log... how would the code be if I wanted the questions to be shown as <h2> for example? I tried: DataList.map(item => item.questions.filter(qitem => <h2>qitem.question.includes(search))</h2> ) I'm new to this stuff and don't know a lot, I apologize.
Here, you can go to this link. I created an example in codesandbox for you to understand it more and how I return an element inside that filtered map.
THANK YOU!!! I can't thank you enough after spending so many hours changing the code and searching for help. Big thank you! 😁
0

I would go with a memo for this as below.

const filteredQuestions = useMemo(()=>{
  var filteredQues =[]
  vv.forEach((p,index) => {
    p.questions.forEach((eachQues, _i)=>{
        if(search==='' || eachQues.question.toLowerCase().includes(search.toLowerCase())){
            filteredQues.push(eachQues);
        }
      })
    
    });
    return filteredQues
},[search]);

Then use filteredQuestions in the render to render filtered questions. I can also convert the above one to a memoized react component and use that directly.

Note: I haven't added conditional checks here.

1 Comment

I'm sorry but I really don't know how to use this code in my project. - I'm extremely new to coding 😞

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.