L
L
Ludmila2017-04-06 20:14:11
JavaScript
Ludmila, 2017-04-06 20:14:11

Can't understand simple js. Kick in the right direction?

Good day!
I apologize in advance for the noob question, but it has its place. I started to learn js - here I am trying to solve a problem. But for some reason there is not enough intelligence (or not enough knowledge) ... I ask for help.
The task is as follows:
We have an array with English words (for example - 7 pieces - and maybe 100), we ask the user to enter a letter, according to which we display the word in our array. If not, we write that this is not found.
How to search for a letter in an array element? You need to access the element somehow.

var libraryLetter = ["book", "car", "bank", "near", "between", "map", "dog"];
        var userLetter = prompt("Укажите буквы через запятую");

        for (var i = 0; i < libraryLetter.length; i++) {            
            if(libraryLetter.indexOf(userLetter) == true){
                    ????
               }else {
                       console.log("Совпадений не найдено");
                        }
        };

Ps And now I feel that I am stupid somewhere, but where ...? Somehow the logic doesn't quite work.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
lemme, 2017-04-06
@Shadow_Princess

https://developer.mozilla.org/en/docs/Web/JavaScript...

function inArray(arr, str) {
  return arr.filter(function(item) {
  	return item.indexOf(str) !== -1
  })
}

var words = inArray(libraryLetter, 'a')

if (words.length > 0 ) {
  console.log(words)
} else {
  console.log('Совпадений не найдено')
}

I
Interface, 2017-04-06
@Interface

Try like this

libraryLetter.filter(word => word.indexOf('a') !== -1)

V
Vladimir Papin, 2017-04-06
@vladpap72

var libraryLetter = ["book", "car", "bank", "near", "between", "map", "dog"];
        var userLetter = prompt("Укажите букву");

        for (var i = 0; i < libraryLetter.length; i++) {            
            if(libraryLetter[i].indexOf(userLetter) == 0){
                    console.log("Совпадение " + libraryLetter[i]);
               }else {
                       console.log("Совпадений не найдено");
                        }
        };

This is the index of the found match, if the index is 0 then it means that it libraryLetter[i]starts withuserLetter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question