0

i have an array with JavaScript.

var arrays = ['Google', 'Yahoo', 'Bing'];

console.log( $.inArray( 'Google', arrays ) ); // return -1
console.log( $.inArray( 'google', arrays ) ); // return 0

I want return always -1 for booth Google, google, GOOGLE, gooGle, or other character combined with lowercase and uppercase.

*Google only example, the words is dynamic.

Opsional
  • 543
  • 4
  • 14
  • https://stackoverflow.com/questions/3390930/any-way-to-make-jquery-inarray-case-insensitive – epascarello Feb 04 '18 at 01:13
  • *return always -1 for both Google, google, GOOGLE, gooGle*? did you mean? *return always 0 for both Google, google, GOOGLE, gooGle*. – Ele Feb 04 '18 at 01:21
  • return `-1` for "Google"? But that is present in arrays. – Mamun Feb 04 '18 at 01:22

1 Answers1

1

You have a typo in your question, you've meant:

I want return always 0 for booth Google, google, GOOGLE, gooGle 
                     ^

The jQuery function $.inArray executes case-sensitive comparison, so, G !== g

What you can do, is convert to either upper or lower case both Google string and values within Arrays. Further, your array arrays will contain the original values after the conversion.

With function map you can accomplish that very smoothly.

var arrays = ['Google', 'Yahoo', 'Bing'];

console.log($.inArray('Google'.toUpperCase(), arrays.map((e) => e.toUpperCase())));
console.log($.inArray('google'.toUpperCase(), arrays.map((e) => e.toUpperCase())));

console.log(arrays);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
See? was printed 0 for both executions and your array arrays contains the same values.

Resources

Ele
  • 33,468
  • 7
  • 37
  • 75
  • Nice! Glad you got your answer in before they marked it duplicate as this answer is much better than the answers in the other post. – user9263373 Feb 04 '18 at 01:55