skip to Main Content

I have two filter function but is possible to be in one line?
Check my code:

this is work fine but is possible to be on one line?

2

Answers


  1. Boolean is just filtering for truthy values, so you can write the filter with just &&:

    let newValue = objectVersion.filter((al) => al && (al.status || al.data));
    
    Login or Signup to reply.
  2. Well, filter() returns an array, and filter() can be called on an array. Which the code shown already demonstrates. So you can certainly remove the intermediate variable and just call filter() directly on the result of the previous filter() operation:

    let newValue = objectVersion.filter(Boolean).filter((al) => al.status || al.data);
    

    You can also combine the logic into a single call to filter(). What is Boolean in this case? Is it just looking for any values which are "truthy"? If so then you can do something like this:

    let newValue = objectVersion.filter((al) => al && (al.status || al.data));
    

    Or if it’s meant here to represent a function that you otherwise pass to filter() then you can invoke it just the same:

    let newValue = objectVersion.filter((al) => yourFunction(al) && (al.status || al.data));
    

    Basically, yes… You can combine any boolean expressions into one larger expression or alternatively you can chain as many calls to filter() (or any other array method which returns an array) as you like.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search