How do I make Array.indexOf() case insensitive?
Solution 1:
ES2015 findIndex:
var array = ['I', 'hAve', 'theSe', 'ITEMs'],
indexOf = (arr, q) => arr.findIndex(item => q.toLowerCase() === item.toLowerCase());
console.log( indexOf(array, 'i') ) // 0
console.log( indexOf(array, 'these') ) // 2
console.log( indexOf(array, 'items') ) // 3
Solution 2:
In ECMA-262, 5th edition, you could use Array.prototype.some
for this.
var array = [ 'I', 'hAve', 'theSe', 'ITEMs' ];
var query = 'these'.toLowerCase();
var index = -1;
array.some(function(element, i) {
if (query === element.toLowerCase()) {
index = i;
return true;
}
});
// Result: index = 2
Solution 3:
Easy way would be to have a temporary array that contains all the names in uppercase. Then you can compare the user input. So your code could become somthing like this:
function delName() {
var dnameVal = document.getElementById('delname').value;
var upperCaseNames = names.map(function(value) {
return value.toUpperCase();
});
var pos = upperCaseNames.indexOf(dnameVal.toUpperCase());
if(pos === -1) {
alert("Not a valid name");
}
else {
names.splice(pos, 1);
document.getElementById('canidates').innerHTML =
"<strong>List of Canidates:</strong> " + names.join(" | ");
}
}
Hope this helps solve your problem.