Champion
Champion

Reputation: 774

Filter out null value from array in React

I want to skip all null value from array in React This is a part of my code. I've added filter before map function but it looks not working.

componentDidMount(){
        client.getEntries({content_type:'formRequest'}).then(response => {
            this.setState({qoutes: response.items});
        }).catch(e => {
        console.log(e);
        });
    }

render(){

        const user = "name";
        const qoutes = this.state.qoutes
        .filter(i => i !== null)
        .map((qoute, i) => 
        user === qoute.fields.user || user === qoute.fields.company ?
        <QoutesListItem id={i} key={i} qoute={qoute} />
        : null)

        return(<div>{qoutes}<div>)

enter image description here

I tried to make function like this, but it does not work as well

const qoutes = this.state.qoutes.filter((qoutes)=>{
    if(qoutes !== null ) {
      return qoutes;
    }}).map((qoute, i) => 

How can I avoid null value and get available data (in my case only three objects)

Upvotes: 0

Views: 4066

Answers (2)

Drew Reese
Drew Reese

Reputation: 202846

Do both conditional checks in a single reduce pass. If the quote is truthy and the fields has a match user or company for user, push the JSX into result array.

const qoutes = this.state.qoutes.reduce(
  (quotes, quote, i) => {
    if (
      quote &&
      quote.fields &&
      (user === quote.fields.user || user === quote.fields.company)
    ) {
      quotes.push(<QoutesListItem id={i} key={i} qoute={quote} />);
    }
    return quotes;
  },
  [] // initial empty quotes result array
);

const quotes = [null, null, null, {
  fields: {
    user: 'name'
  }
}, null, {
  fields: {
    company: 'name'
  }
}];

const user = "name";

const quotesRes = quotes.reduce(
  (quotes, quote, i) => {
    if (
      quote &&
      quote.fields &&
      (user === quote.fields.user || user === quote.fields.company)
    ) {
      quotes.push(`<QoutesListItem id={${i}} key={${i}} qoute={${quote.fields.user || quote.fields.company}} />`);
    }
    return quotes;
  }, [] // initial empty quotes result array
);

console.log(quotesRes);

FYI, anytime you see map/filter or filter/map should be a good indication to use a reduce function.

Upvotes: 2

Rashomon
Rashomon

Reputation: 6762

Filter the results again to remove the null elements from the second map:

render(){
  const user = "name";
  const qoutes = this.state.qoutes
    .filter(q => !!q)
    .map((qoute, i) => 
        user === qoute.fields.user || user === qoute.fields.company ?
          <QoutesListItem id={i} key={i} qoute={qoute} />
          : 
          null)
    .filter(q => !!q) // Filter falsy values

  return(<div>{qoutes}<div>)

Upvotes: 2

Related Questions