Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Search for first character in an Array

I'm trying to find the first character in an Array in JavaScript.

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

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

And here's my Array list.

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

If the user only wants arrays with W's, only words with a W in the first letter is shown. (Like "where" or "why")

I do not have a lot of experience with JavaScript from before and I have been sitting with this problem for ages.

like image 262
Jason Stackhouse Avatar asked Dec 16 '22 23:12

Jason Stackhouse


1 Answers

There's indexOf() method of an array/string which can provide you with a position of a letter. First letter has a position of 0(zero), so

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 a jsFiddle for it. Before running open the console(Chrome: ctrl+shift+i, or console in FireBug) to see resulting arrays.

like image 82
lukas.pukenis Avatar answered Feb 21 '23 16:02

lukas.pukenis