Filter an array of items by "category"


(Andre Glegg) #1

Hi guys, I would say i’m still new to writing a lot of javascript and even newer to react. I recently write this to filter the displayed portfolio items on a page i’m working on.

let items = "Loading portfolioItems...";
        if (this.props.portfolioItems) {
            items = this.props.portfolioItems
                .map((item, i) => {
                    //console.log(item);
                    if (this.state.currentCategory === "all") {
                        return (
                            <PortfolioItem key={i} thumb={item.thumb} name={item.name} desc={item.desc}/>);
                    }
                    else if (item.category === this.state.currentCategory) {
                        return (
                            <PortfolioItem key={i} thumb={item.thumb} name={item.name} desc={item.desc}/>);
                    }
                });
        }

It works but is it the right way to do it… ? if not what are the disadvantages ?


(Lokesh Chandawar) #2
const items = Array.isArray(this.props.portfolioItems)
        ? this.props.portfolioItems.map(
              (item, i) =>
                  (this.state.currentCategory === 'all' || this.state.currentCategory === item.category) &&
                  <PortfolioItem key={i} thumb={item.thumb} name={item.name} desc={item.desc} />
          )
        : 'Loading portfolioItems...'

Compare above code with your code. you will find following changes

  1. Validate exact condition if portfolioItems is array then only apply loop else display the default message
  2. try to avoid the use of let instead of that use const.
  3. Combine the two if with OR condition ( || ) because the return value is same and removed repetitive code ( calling ) if you are showing different component then you can separate out this if the condition

(Andre Glegg) #3

Awesome it works!
Thanks for the tips, I’m gonna practice as much as I can so I can write better code.