Mike Mike - 6 months ago 9
Javascript Question

How to solve this using arrays and for loops?

I have a string given, such as "hello my name is James and what is your name and what is your name"
It should output "hello my name is james and what 4 your 3 6 7 4 8 3"
So Basically what happens is that the if the words get repeated then they get replaced with the position of where the first word occurred. For instance, if the sentence is "the house is the best" it would replace the repeated word which is "the" with the position of where the first "the" occurred. so it should output "the house is 1 best"

Answer

First, you want to split the string at every space. You do this with the split method.

var sentence = "hello my name is James and what is your name and what is your name";
var words = sentence.split(" ");

Then you want two nested for loops. The first one goes through each word, and the second one checks for each word before it. If they are the same, it makes

for (var i = 0; i < words.length; i++) {
    for (var j = 0; j < i; j++) {
        if (words[i] == words[j]) {
            words[i] = j + 1;
            break;
        }
    }
}

Then you want to turn the array back into a string. Do this with the join method.

var newSentence = words.join(" ");

This method doesn't work correctly if there is any punctuation or capital letters. Capital letters can be fixed by using the toLowerCase method on the original string. Punctuation will be more complicated, I'll be able to figure it out if you give me some time.