Reputation: 21
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.
Upvotes: 0
Views: 595
Reputation: 2055
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.
Upvotes: 1
Reputation: 1321
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.");
Upvotes: 0
Reputation: 10529
Just little mistakes:
prompt
in string
: string = prompt(string);
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);
}
Upvotes: 0