Accessing array values

Accessing array values
0

#1

var arr =[];
function findLongestWord(str) {
str = str.split(’’).join(’’); //Splits the string, makes array
console.log(str);
for(var i=0; i<str.length; i++) { // for every whitespace index is stored in arr.
if (str[i].indexOf(’ ') >= 0){
if (arr.length === null) {
arr.push(i);
}
else {
arr.push(i); // the problem is here
console.log(arr);
}
}
}
// return Math.max.apply(Math, arr);
}

findLongestWord(“The quick brown fox jumped over the lazy dog”);

The values arr has is [3, 9, 15, 19, 26, 31, 35, 40]. Is there any way I can access the array value that is before the one I’m at. For example: When i=9 I want to access value 3 and push it in arr at the else statement.


#2

I think you are confused at this line:
str = str.split('').join('');

At the end nothing’s changed; it’s still the same as the string str.

Why not split at spaces? That way you have a nice array of words. Then instead of working with indexes you’ll now be working with words.


#3

Yeah, the join was unnecessary. I made the change and split at spaces. I saw the solution you are suggesting of. I was just wondering if there is a way to access the value at a specific index while looping.

Thank you @kevcomedia


#4

If you’re looping with variable x and need to access an element that’s prior to index x you can simply index the variable with x-1.

You’ve to make sure though that it won’t happen when x equals 0 as you would try to access it with a negative index.


#5

In my case the variable x has value 3 for the first time the loop is true. The second time it’s 9. So x-1 won’t get me the value I’m looking for.


#6

Sorry, I missed the fact you were working with two arrays. It seems to me that you are particularly interested in the last element of the arr array. If that’s so then you can use the length of arr and subtract one from it to access the last element.