Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do loose equality comparision using array.includes

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.

like image 797
Jagrati Avatar asked Mar 07 '26 08:03

Jagrati


2 Answers

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"));
like image 113
T.J. Crowder Avatar answered Mar 09 '26 20:03

T.J. Crowder


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.

like image 36
Lanci Avatar answered Mar 09 '26 21:03

Lanci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!