Home > Software engineering >  what is the use of .length in array.filter in javascript
what is the use of .length in array.filter in javascript

Time:08-15

What is the use of .length in array-filters

      const filteredMatchedProfile=matchedProfiles?.filter(
          (matchedprofile)=>
              matchedprofile.matches.filter(
                 (profile)=>
                     profile.user_id==userID).length>0)

Use of .length filter in arrays?

CodePudding user response:

The inner filter is just a common, but poor, way to see if any element in the array matches the predicate supplied by the function: If the new array filter creates has any elements in it (.length > 0), at least one element matched the predicate.

The better way to do that is with some

const filteredMatchedProfile = matchedProfiles?.filter((matchedprofile) =>
    matchedprofile.matches.some((profile) => profile.user_id == userID)
);

Using some more clearly indicates what you're doing, doesn't create an unnecessary throw-away array, and stops as soon as it knows the result.

It's one of the two common antipatterns around filter:

  1. someArray.filter(predicateFunction).length > 0 or === 0 should be replaced with someArray.some(predicateFunction) and !someArray.some(predicateFunction), respectively.

  2. someArray.filter(predicateFunction)[0] should be replaced with a call to find: someArray.find(predicateFunction).


¹ A better name for some would be any, but unfortunately when it was being added to JavaScript, a survey of code in the wild using libraries and such found that adding a standard any method would break existing code. :-(

CodePudding user response:

.length checks if the array has some items in it if length is greater than 0.

  • Related