DEV Community

Cover image for Answer: JS Array.filter Method Returns an Empty Array
SpeedingRoo
SpeedingRoo

Posted on

Answer: JS Array.filter Method Returns an Empty Array

The problem is the filter method is expecting a return value, and you’re not returning anything.

There are 2 ways you can fix this, both do the same thing.

filter(p => p.category === this.category)

or

filter(p => { return p.category === this.category; })

Made the same mistake, turns out the cause was very simple and basic: When I try to act like a pro and use the simplified sytax of the arrow function, I failed to remember that if the function body only has ONE STATEMENT, I need to :

EITHER explicitly return whatever sh1t I am trying to return, if I was using the { } to enclose my statement,

    let newData = data.filter(i=>{
      return i.address!==item.address
    })
Enter fullscreen mode Exit fullscreen mode

OR I don't use the { } and just throw my only one statement right after the arrow and call it a day.

    let newData = data.filter(i=>
      i.address!==item.address
    )
Enter fullscreen mode Exit fullscreen mode

That's it

What I did was that I USED the { }, but I did not write 'return' keyword, so nothing works and my filtered array remains empty.

    //  Won't Work !!
    let newData = data.filter(i=>{
      i.address!==item.address
    })
Enter fullscreen mode Exit fullscreen mode

Top comments (0)