This code currently does the job I am asking for, but I was wondering if there was a better way, as calling names[i][j]
seems impractical.
var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"]; for(var i = 0; i < names.length; i++) { for(var j = 0; j < names[i].length; j++) { if(names[i][j] === "J" || names[i][j] === "j") { console.log("Name with the letter J detected!"); } } }
You can use includes
method in combination with filter
method which applies a provided
callback method to every item in the array.
var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"]; console.log(names.filter(a=>a.toLowerCase().includes("j")));
Simply use with indexOf('j')
.Iterate with array with Array#forEach
then convert the each text into lowercase
.Then match the indexof j
var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"]; names.forEach(a => a.toLowerCase().indexOf('j') > -1? console.log('Name with the letter J detected!'):'')
If you...
Array.prototype.some
. Array.prototype.find
. Array.prototype.filter
. var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"]; var someHasJ = names.some(n => n.toLowerCase().includes("j")); var hasJ = names.find(n => n.toLowerCase().includes("j")); var allWithJ = names.filter(n => n.toLowerCase().includes("j")); if (someHasJ) { console.log("Name with the letter J detected!"); } if (hasJ) { console.log(hasJ); } if (allWithJ.length > 0) { console.log(allWithJ); }
You could use Array#join
for joining all items and check with Array#indexOf
.
var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"]; if (names.join().toLowerCase().indexOf('j') !== -1) { console.log('found!'); } else { console.log('not found!'); }
Just use something like this, using some() and indexOf():
var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"];
function hasThis(arr, str){
return arr.some(function(x) {
return x.toLowerCase().indexOf(str.toLowerCase()) > -1;
});
}
hasThis(names, 'J'); //return true
hasThis(names, 'Xhj'); //return false
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.