0

I am getting this typeError with split when I try to run this js. I am unsure of how to fix it, I defined it properly as shown in my textbook.

var current;
var string;

console.log("Enter words separated by spaces.");
prompt(string);

var array = [];
array = string.split(" ");

for(i = 0; i < array.length; i++)
    {
        var frequency = 0;
        current = array[i];
            for(i = 0; i < array.length; i++)
                {
                    if(current === array[i])
                        frequency++;
                }
        console.log(current + " - " + frequency);    
    }
}

When running properly the function should produce an output like so: hey - 1. It counts the frequency of each unique word and displays next to the word the amount of times it appears in the string. Any help would be greatly appreciated thank you.

slowbro46
  • 21
  • 3

3 Answers3

1

the main problem is that you were not reading string in from your prompt. I have stored the result as s in my example below.

Also you were using i again in your second for loop. Use another letter for this (the convention is j):

var current;
var string;
var s;

console.log("Enter words separated by spaces.");
s = prompt(string);

var array = [];
array = s.split(" ");

console.log(array);

for(i = 0; i < array.length; i++){
        var frequency = 0;
        current = array[i];
        
        for(j = 0; j < array.length; j++){
            if(current === array[j]) frequency++;
        }
                
        console.log(current + " - " + frequency);    
    }

I hope this helps.

Mike Poole
  • 1,958
  • 5
  • 29
  • 41
0

Instead of doing split, you can do .splice.

I believe this link is helpful.

However, first, you would have to search through the array for " ". You can implement this through string.search(" "), which returns where the " " is found.

Furthermore, your syntax for prompt is wrong, it should be:

var something = prompt("Enter words separated by spaces.");

Chris
  • 1,206
  • 2
  • 15
  • 35
0

Just little mistakes:

  1. store the prompt in string: string = prompt(string);
  2. give second for loop another variable j, so i won't overwritten.

var current;
var string;

console.log("Enter words separated by spaces.");
string = prompt(string);

var array = [];
array = string.split(" ");

for (i = 0; i < array.length; i++) {
  var frequency = 0;
  current = array[i];
  for (j = 0; j < array.length; j++) {
    if (current === array[j])
      frequency++;
  }
  console.log(current + " - " + frequency);
}
tom
  • 9,550
  • 6
  • 30
  • 49