JavaScript - finding the first character in an array

I am trying to find the first character in an array in JavaScript.

I have a random function (not the best, but I'm going to improve it):

function random() { var Rand = Math.floor(Math.random()*myArray.length); document.getElementById('tr').innerHTML = myArray[Rand]; } 

And here is a list of my arrays.

 myArray = ["where", "to", "get", "under", "over", "why"]; 

If the user only needs arrays with W, only words with W in the first letter are displayed. (Like "where" or "why")

I do not have much experience with JavaScript before, and I have been sitting with this problem for a long time.

+4
source share
2 answers

Here's indexOf() an array / string method that can provide you with the position of the letter. The first letter has position 0 (zero) , therefore

 function filter(letter) { var results = []; var len = myArray.length; for (var i = 0; i < len; i++) { if (myArray[i].indexOf(letter) == 0) results.push(myArray[i]); } return results; } 

Here is jsFiddle . Before starting, open the console (Chrome: ctrl + shift + i or the console in FireBug) to see the resulting arrays.

+6
source

You can filter an array containing only specific values, such as those starting with 'w'

 var words = ["where", "to", "get", "under", "over", "why"]; var wordsWithW = words.filter(function(word) { return word[0] == 'w'; }); var randomWordWithW = wordsWithW[Math.floor(Math.random() * wordsWithW.length]; ... // operate on the filtered array afterwards 

If you plan on supporting older browsers, you might consider using underscore.js or Prototype.

When using underscores, you can simply write this:

 var randomWordWithW = _.chain(words).filter(function(word) { return word[0] == 'w'; }).shuffle().first().value() 
+5
source

Source: https://habr.com/ru/post/1415562/


All Articles