Tayls
Tayls

Reputation: 11

Returning multiple index values from an array using Javascript

I have an array containing the individual letters of a word and i want to search the array to return the index values of certain letters. However, if the word contains more a letter more than once (such as 'tree') the programme only returns one index value.

This is a sample of the code:

var chosenWord = "tree";     
var individualLetters = chosenWord.split('');
var isLetterThere = individualLetters.indexOf(e);
console.log(isLetterThere);

this code will return the number '2', as that is the first instance of the letter 'e'. How would i get it to return 2 and 3 in the integer format, so that i could use them to replace items in another array using the .splice function.

Upvotes: 0

Views: 5196

Answers (5)

C3roe
C3roe

Reputation: 96339

indexOf takes a second parameter, as the position where it should start searching from.

So my approach would be:

function findLetterPositions(text, letter) {
    var positions = new Array(),
        pos = -1;
    while ((pos = text.indexOf(letter, pos + 1)) != -1) {
        positions.push(pos);
    }
    return positions;
}

console.log(findLetterPositions("Some eerie eels in every ensemble.", "e"));

http://jsfiddle.net/h2s7hk1r/

Upvotes: 1

Benjamin De Cock
Benjamin De Cock

Reputation: 230

var getLetterIndexes = function(word, letter) {
  var indexes = [];
  word.split("").forEach(function(el, i) {
    el === letter && indexes.push(i);
  });
  return indexes;
};

getLetterIndexes("tree", "e"); // [2, 3]

Upvotes: 0

Etheryte
Etheryte

Reputation: 25319

An alternative using string methods.

var str = "thisisasimpleinput";
var cpy = str;
var indexes = [];
var n = -1;
for (var i = cpy.indexOf('i'); i > -1; i = cpy.indexOf('i')) {
  n += i;
  n++;
  indexes.push(n);
  cpy = cpy.slice(++i);
}
alert(indexes.toString());

Upvotes: 0

Mic
Mic

Reputation: 4004

Loop through it as here:

var chosenWord = "tree";
var specifiedLetter = "e";
var individualLetters = chosenWord.split('');
var matches = [];
for(i = 0;i<individualLetters.length;i++){
  if(individualLetters[i] == specifiedLetter)
    matches[matches.length] = i; 
}

console.log(matches);

Upvotes: 0

brso05
brso05

Reputation: 13232

You could write a function like this:

function indexesOf(myWord, myLetter)
{
    var indexes = new Array();
    for(var i = 0; i < myWord.length; i++)
    {
        if(myWord.charAt(i) == myLetter)
        {
            indexes.push(i);
        }
    }
    return indexes;
}
console.log(indexesOf("tree", "e"));

Upvotes: 0

Related Questions