I recently learned of a great JavaScript method I'd never used. It was brought to my attention by Wes Bos. The some() method is a convenient way to...
For further actions, you may consider blocking this person and/or reporting abuse
I think
.includes()
is better than.some()
for checking if an array contains a value or not:.some()
is good for other use-cases like finding if a value > 15 exists in an array:I agree,
.includes()
would be a better solution for the specific problem I laid out. I just wanted to give a simple bit of code to illustrate how.some()
works.I'll try and add a second example to show another use-case.
Thanks!
I was thinking the same string, but
some
reminds me of a function I wrote a long time ago (in PHP) calledsomeValidStrings
which checked an array to make sure that there was at least 1 value that was correctly typed as a String, and also fulfilled some other business logic on what was considered "valid" (think: string length, ends with a run of 3 numbers, etc.). This is a case thatsome
would excel at with the function callback rather than just looking for a certain value.I was thinking that I could use
find
for the same purpose, but I see that there's a logical benefit to returning a boolean directly rather than a value that would have to be checked. I imaginefind
,some
andfindIndex
work very similarly and only really differ in what they return.Nice post!
A strange example 😅:
It is quite handy!
I used
.some()
coupled with.includes()
a while back to cross-reference two string arrays to make sure the user had at least one of the required roles for an action. The benefit of.some()
here is that it will return true no matter how many of the iterations are false, as long as one of them is true.Reminds me of LINQ, very useful to have this in JS. Thanks for the post.
can't we use simply
animals.indexOf("snakes") > -1
jsperf
You can! That's the beauty of code, there's usually more than one way to solve a problem. It all comes down to preference and the task at hand.
Nice post Matt and very useful!
Thank you!
P.S. I also use .includes() but careful, ie doesn't support it.
This could also be accomplished with filter and then calling length, right?
Yep!
Amazing, thank you for sharing
This could be very useful ! Never ever heard of this function or used it! Seems really nice together with the arrow function syntax! Thank you!!
Interesting. I can see some immediate uses now for my rss project. Thank you