Array.includes does a strict comparison of array elements.
var array1 = [1, 2, 3];
console.log(array1.includes(2)); // return true
console.log(array1.includes("2")); // return false
But I want the result to return true in second case as well.My main goal is to know whether an array contains an element. Please suggest how this can be achieved.
You can't use includes, since it always uses strict equality; you can use some instead:
console.log(array1.some(e => e == "2"));
some calls the callback you provide for the elements, in order, until your callback returns a truthy value, in which case some stops looping and returns true. If your callback never returns a truthy value (including because it was never called because the array was empty), some returns false.
some was added in ES5 (2009).
Live example:
const array1 = [1, 2, 3];
console.log(array1.some(e => e == "2"));
If the array is always formed by numbers and you are sure to pass a string to be checked, you could also use parseInt():
console.log(array1.includes(parseInt("2")));
Please note that this would work also if you were to pass an integer to the parseInt but that is is not correct since parseInt expect a string as a parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With