I am using includes
to know if the element exists in my array:
var array = [1,2,3,4,5]
array.includes(1)
Console => true
All very well, but now I try to put more options to the functionincludes
How to verify that there is at least one element out of several in the array?
var array = [1,2,3,4,5]
array.includes(0,2,3,8)
As we can see the 2 and 3 exist in our array, but if I run this I get false
.
array.includes(0,2,3,8)
Console => false
If you want to check if there is at least one element you can use
some()
that returnstrue
orfalse
depending on whether the condition you set in the function is met or not.find()
, unlikesome()
returns the value of the first element that matches , so you have to check thelenght
result, for that reason, for this specific problem I understand that it is bettersome()
.You could use the function
find()
and if it finds a match in any of its iterations it will return that number, after that you could change that number to its expressionboolean
.Update : validation done for when the value found is 0, since it would not apply to cast
!!
.If what you want is to know if there is any element in your array, the simplest thing would be to use
This will return the number of elements that you have inside your array, and to know if a specific element is found you could use
It would also be an option although it works differently from includes it does basically the same function, although the includes function is newer...
You can verify it with this
Array.length
:You can search for such an element as an array using
map
.With the array
[0,2,3,8]
you can ask for each one. Are you including the 0? and the 2? and the 3? and the 8? within[1,2,3,4,5]
. What this does is ask for everyone, and an array like the following is left:Finally, you can ask if there exists in the array
true
, which in this case is true.Code: