yavnelf
yavnelf

Reputation: 355

How can I implement the filter method to this code without deleting map method?

I would like to make my array of jokeComponents gets filtered to only display those that have fewer than X number of characters in the question.

How can I implement the filter method to this code without deleting map method?

import React from "react"

import Joke from "./Joke"
import jokesData from "./jokesData"

function App() {
    const jokeComponents = jokesData.map(joke => <Joke key={joke.id} question={joke.question} punchLine={joke.punchLine} />)
    
    return (
        <div>
            {jokeComponents}            
        </div>
    )
}

export default App

Upvotes: 0

Views: 46

Answers (4)

Lorick
Lorick

Reputation: 11

import React from "react"

import Joke from "./Joke"
import jokesData from "./jokesData"

function App() {

  const filteredJokes = jokesData.filter(joke => joke.question.length > X);

   return filteredJokes.map(joke => <Joke key={joke.id} {...joke}  />)
}

export default App


Upvotes: 0

Priyanka Panjabi
Priyanka Panjabi

Reputation: 441

This is initially filter out array with elements having question length less than value X.

import React from "react"

import Joke from "./Joke"
import jokesData from "./jokesData"

function App() {
    const jokeComponents = jokesData.filter(ele=>{ele.question.length>X}).map(joke => <Joke key={joke.id} question={joke.question} punchLine={joke.punchLine} />)
    
    return (
        <div>
            {jokeComponents}            
        </div>
    )
}

export default App

Upvotes: 0

Patrick Bateman
Patrick Bateman

Reputation: 68

You could so something like this? Whereby you filter your array of components by perform your predicated function against the question prop. And then render the filtered array (if that's the intended outcome)

import React from "react"

import Joke from "./Joke"
import jokesData from "./jokesData"

function App() {
    const jokeComponents = jokesData.map(joke => <Joke key={joke.id} question={joke.question} punchLine={joke.punchLine} />);
    const filteredJokes = jokeComponents.filter((component) => component.props.question.length > 2);
    
    return (
        <div>
            {filteredJokes}            
        </div>
    )
}

export default App

Upvotes: 0

Badmaash
Badmaash

Reputation: 795

jokesData.filter(joke => joke.question.length > X).map(joke => <Joke key={joke.id} question={joke.question} punchLine={joke.punchLine} />)

Try this.

Upvotes: 2

Related Questions