Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.indexOf insensitive data type

I have been using Array.indexOf in the Google Chrome console, I tried these codes

[1,2,3].indexOf(3);
[1,2,"3"].indexOf("3");

They all returned 2, but when I tried these codes

[1,2,"3"].indexOf(3);
[1,2,3].indexOf("3");

They all returned -1. I want it also return 2, how could I do that? Thanks for your help, time, and effort!

like image 234
Hzzkygcs Avatar asked May 25 '17 04:05

Hzzkygcs


2 Answers

expanding on guest271314's post: cast both of the values to a string. This will also work for numbers and strings

val = true

console.log([1,2,"true"].findIndex(item => String(item) === String(val)))
like image 144
Anis Jonischkeit Avatar answered Dec 03 '22 01:12

Anis Jonischkeit


You can use Array.prototype.findIndex(), == operator

var n = 3;

console.log(
  [1,2,3].findIndex(el => el == n)
, [1,2,"3"].findIndex(el => el == n)
)
like image 28
guest271314 Avatar answered Dec 03 '22 02:12

guest271314