简体   繁体   中英

What is the best way to loop through an index of an array to search for a certain letter?

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...

  • ...want to detect that there's at least one occurrence of a given criteria, use Array.prototype.some .
  • ...want to get the first occurrence of a given criteria, use Array.prototype.find .
  • ...want to get all occurrences of a given criteria, use 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM