In this context, you can use array#some
,
var data = [ 'one', 'two', 'three', 'four', 'three', 'five', ]; found = data.some(function(x) { return x == "three"; }); console.log(found);
If you use filter
, then the array will be filtered based on the true value returned inside the callBack
function. Therefore, if any matches found a value, if the function returned with the value true
, then the element at this particular iteration will be assembled into an array
, and finally, the array will be returned.
Therefore, in your case, ["three", "theree"]
will be returned as a result. If you do not have "three"
then an empty array will be returned. In this context, you need to do an additional check to find the true value in it.
Example:
var res = arr.filter(itm => someCondition); var res = !!res.length; console.log(res);
So, to avoid this situation, we use Array # some.
source share