user495688
user495688

Reputation: 973

how to get index of array in javascript

I have a problem in obtaining the index, if in an array there are some similar words but with a different index position and when I select one of the word, the index that I get is not from words but from which I select the same word in previous position

for example I have a sentence:

The Harvest is the process of gathering

the bold word is the word that I choose..

this is my code:

var str = "The Harvest is the process of gathering";
var myArray = str.split ("");
var Select  = "the";

and I have a function like this:

function getIndex (arrayItem, item) {
   for (var x = 0; x <arrayItem.length; x + +) {
    if (arrayItem [x] == item) {
     return x;
     }
   }
   return -1;
   }

var idx = getIndex (myArray, Select);

how to get that index?

Upvotes: 1

Views: 7900

Answers (2)

DLS
DLS

Reputation: 5491

Just to point out, fix this one line in your code and you should get what you are looking for

var myArray = str.split (" "); //instead of splitting it character by character, split it where spaces appear. That should get the correct result. Your quotes don't have a space, hence the results you are getting. link text

Check out code here . Make sure to have firebug on to see the results.

Upvotes: 0

Jacob Relkin
Jacob Relkin

Reputation: 163318

You might want to avoid this altogether and use the String object's indexOf method:

var str = "The Harvest is the process of gathering";
var idx = str.indexOf('the');

Upvotes: 5

Related Questions