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
:
someArray.filter(predicateFunction).length > 0
or=== 0
should be replaced withsomeArray.some(predicateFunction)
and!someArray.some(predicateFunction)
, respectively.someArray.filter(predicateFunction)[0]
should be replaced with a call tofind
: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.