Array.indexOf insensitive data type
Asked Answered
D

2

7

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!

Drops answered 25/5, 2017 at 4:53 Comment(4)
change [1,2,"3"].indexOf("3"); and [1,2,3].indexOf(3);Litchfield
probably just turn everything into a string then inside indexOfDoreathadoreen
Why are you storing different datatypes in the array? Can't you make sure that you convert everything to numbers first?Ingurgitate
Good Idea, @A.Lau . Thanks A. Lau and EdisonDrops
S
7

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)))
Serajevo answered 25/5, 2017 at 5:10 Comment(1)
If you are converting value to string, use ===Cannell
U
7

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)
)
Ubiquitarian answered 25/5, 2017 at 5:0 Comment(4)
Thanks for your effort... it works well between string and integer, but doesn't work well between boolean and string... But I appreciate your effort...Drops
What do you mean by "between boolean and string"?Ubiquitarian
Sorry if my comment not really clear, this is an example var n = true; console.log( [1,2,true].findIndex(el => el == n), [1,2,"true"].findIndex(el => el == n)) Both returns 0.Drops
That is a different requirement than original Question.Ubiquitarian
S
7

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)))
Serajevo answered 25/5, 2017 at 5:10 Comment(1)
If you are converting value to string, use ===Cannell

© 2022 - 2024 — McMap. All rights reserved.