简体   繁体   中英

finding the words with given letters in an array

I'm new to coding, can you help me with this small JavaScript code? the problem that I am facing is that I can't console.log the words in the arr array

var arr =["wide","wiiii", "dwww", "not"]
var lett = ["i","w","d","e"]
var c = 0;
for(  i=0;i<arr.length;i++){
  for ( x=0;x<arr[i].length;x++){
    for (z=0;z<lett.length;z++){
      if (arr[i][x]==lett[z] ){
        c++
        if(c == lett.length-1){
          console.log(arr[i])
        }
      }
    }
    
  }
}

the output should look like this

wide
wiiii
dwww

@Vishnudev I found the error: the code that you gave me logs the words that have AT LEAST one letter that is in the lett [], and that's not what I want. see, if in the words array there is ["wide","wzzxx","this word has the letter j in it"] your code gives this output:

wide
wzzxx
this word has the letter j in it

but what I need is this as output:

wide

Use Array.prototype.filter with Array.prototype.every

 const arr =["wide","wiiii", "dwww", "not"]; const lett = ["i","w","d","e"]; const values = arr.filter(word => word.split('').every(c => lett.includes(c))); console.log(values.join('\n'));

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