JavaScript TypeError: cannot read property 'split' of undefined - javascript

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.

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.

Just little mistakes:
store the prompt in string: string = prompt(string);
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);
}

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.");

Related

Split string without any built-in functions

I need a function that works like split
var string = "a|b|c"
console.log(string.split('|'))
to get a string and split it using loop
function splitstr(str, charToSplit){
}
I want the output of ('a|b|c', '|') to be ["a", "b", "c"]
Here is a slightly simpler solution that works correctly:
function splitStr(str, separator) {
const parts = [];
let nextPart = '';
for (let i = 0; i <= str.length; i++) {
if (str[i] === separator || i === str.length) {
parts[parts.length] = nextPart;
nextPart = '';
} else {
nextPart += str[i]
}
}
return parts;
}
console.log(splitStr("abc|abcd|ac", "|"));
You can use the code below.
This code had 8 steps to it.
Loops through the string
Checks if the current item is equal to charToSplit
If it is, it loops through the values in between startIndex and your current index (excluding your current index, which is the character you want to split on)
It first sets the value of output[currentIndex] to an empty string (since using += on something that doesn't exist doesn't work correctly
Then it adds the current letter you are on to output
startIndex is set to your current index + 1 (which is the character after the character that you want to split on)
currentIndex is increased by 1 since you're now on the next set of values
Finally, the code returns output
Note: The final extra loop after the first loop is there to add the last value to your output array.
function splitstr(str, charToSplit) {
var output = [];
var currentIndex = 0;
var startIndex = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] == charToSplit) {
output[currentIndex] = "";
for (var x = startIndex; x < i; x++) {
output[currentIndex] += str[x];
}
startIndex = i + 1;
currentIndex++;
}
}
output[currentIndex] = "";
for (var i = startIndex; i < str.length; i++) {
output[currentIndex] += str[i];
}
return output;
}
console.log(splitstr("abc|abcd|ac", "|"));

cannot detect error. Where is the infinite loop occurring?

// JavaScript Document
var person = prompt("GIVE INPUT", "");
var count = 0;
var array = person.split(",");
var freq = [];
var words = [];
//freq.fill(0);
//words.fill("");
//window.alert(freq[0]);
var i = 0, j = 0;
while (array.length > 0) {
var temp = array[0];
while (j < array.length) {
if (temp == array[j]) {
count = count + 1;
array.splice(j, 1);
//console.log(array);
j = 0;
}
else {
j = j + 1;
}
}
freq[freq.length] = count;
count = 0;
words[words.length] = temp;
}
window.alert(freq + "\n" + words);
The problem is that whenever I run it an infinite loop occurs and no output is shown, I cannot find the error please help if possible. This code is for finding the frequency of the words in a input string with words separated by commas. thank u.
You just need to put var i=0,j=0; inside the while !
while(array.length>0)
{var i=0,j=0;
Working fidddle
You're resetting your loop variable j to 0 on each iteration. This condition if(temp==array[j]) never fails so j is always reset to 0, so while(j<array.length) is always true.
After coming out of the inner While loop, you need to reset j to zero. As the incremental value of j is not allowing it to go again inside the inner loop So array.length is not reducing And we are getting an infinite loop.
// JavaScript Document
var person = prompt("GIVE INPUT", "");
var count=0;
var array = person.split(",");
var freq = new Array();
var words = new Array();
//freq.fill(0);
//words.fill("");
//window.alert(freq[0]);
var i=0,j=0;
while(array.length>0)
{
var temp=array[0];
while(j<array.length)
{
if(temp==array[j])
{
count=count+1;
array.splice(j,1);
//console.log(array);
j=0;
}
else
{
j=j+1;
}
}
freq[freq.length]=count;
count=j=0;
words[words.length]=temp;
}
window.alert(freq+"\n"+words);
It's where for is more useful for consistency. You can replace inner while loop by this for loop:
for(j=a.length-1; j>=0; j--)
if(temp==a[j]) {
count=count+1;
a.splice(j,1);
}
Nevertheless, overall complexity of your counting method can be reduced with data structure like map.
Essential part of your script can be reduced to this:
var counter = new Map();
for (i in array)
counter.set(array[i], (counter.get(array[i])||0)+1);
var freq = Array.from(counter.values());
var words = Array.from(counter.keys());

Doubling each letter in a String in js

I need string Double each letter in a string
abc -> aabbcc
i try this
var s = "abc";
for(var i = 0; i < s.length ; i++){
console.log(s+s);
}
o/p
> abcabc
> abcabc
> abcabc
but i need
aabbcc
help me
Use String#split , Array#map and Array#join methods.
var s = "abc";
console.log(
// split the string into individual char array
s.split('').map(function(v) {
// iterate and update
return v + v;
// join the updated array
}).join('')
)
UPDATE : You can even use String#replace method for that.
var s = "abc";
console.log(
// replace each charcter with repetition of it
// inside substituting string you can use $& for getting matched char
s.replace(/./g, '$&$&')
)
You need to reference the specific character at the index within the string with s[i] rather than just s itself.
var s = "abc";
var out = "";
for(var i = 0; i < s.length ; i++){
out = out + (s[i] + s[i]);
}
console.log(out);
I have created a function which takes string as an input and iterate the string and returns the final string with each character doubled.
var s = "abcdef";
function makeDoubles(s){
var s1 = "";
for(var i=0; i<s.length; i++){
s1 += s[i]+s[i];
}
return s1;
}
alert(makeDoubles(s));
if you want to make it with a loop, then you have to print s[i]+s[i];
not, s + s.
var s = "abc";
let newS = "";
for (var i = 0; i < s.length; i++) {
newS += s[i] + s[i];
}
console.log(newS);
that works for me, maybe a little bit hardcoded, but I am new too))
good luck
console.log(s+s);, here s holds entire string. You will have to fetch individual character and append it.
var s = "abc";
var r = ""
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
r+= c+c
}
console.log(r)
var doubleStr = function(str) {
str = str.split('');
var i = 0;
while (i < str.length) {
str.splice(i, 0, str[i]);
i += 2;
}
return str.join('');
};
You can simply use one of these two methods:
const doubleChar = (str) => str.split("").map(c => c + c).join("");
OR
function doubleChar(str) {
var word = '';
for (var i = 0; i < str.length; i++){
word = word + str[i] + str[i];
};
return word;
};
function doubleChar(str) {
let sum = [];
for (let i = 0; i < str.length; i++){
let result = (str[i]+str[i]);
sum = sum + result;
}
return sum;
}
console.log (doubleChar ("Hello"));

Need to filter out repeating consecutive characters in a string using JavaScript

It is one of the challenges in Codewars, and I am supposed to write a function that will take a string and return an array, in which I can't have two consecutive identical elements. Also, the order should not change.
For example, if I pass a string "hhhhheeeelllloooooohhheeeyyy", then the function should return an array = ["h","e","l","o","h","e","y"].
This is my code.
var uniqueInOrder=function(iterable){
//your code here - remember iterable can be a string or an array
var unique = [];
for( var i = 0; i < iterable.length; i++) {
unique.push(iterable[i]);
}
for( var j = 0, k = 1; j < unique.length; j++, k = j + 1 ){
if(unique[j] === unique[k]){
unique.splice(k,1);
}
}
return unique;
}
so, if I pass a string, such as "hhhhheeeeeellllloooo",it doesn't work as I intend it to because the value of j keeps incrementing, hence I can't filter out all the identical elements.
I tried tweaking the logic, such that whenever the unique[j] === unique[k] the value of j would become zero, and if that's not the case, then things would continue as they are supposed to do.
This got me an infinite loop.
I need your help.
The second for loop is fail because unique.length is not constant during the run.
I think your problem can be solved like this:
var temp = iterable[0];
unique.push(iterable[0]);
for( var i = 1; i < iterable.length; i++) {
if(iterable[i] != temp) {
unique.push(iterable[i]);
temp = iterable[i];
}
}
Hope it helps!
You only need to compare the current index of iterable against the last character in unique:
function(iterable){
var unique = []
for(var i=0; i< iterable.length; i++){
if(unique.length < 1){
unique.push(iterable[i])
} else if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
I think this will help you:
var word="hhhhheeeelllloooooohhheeeyyy"
function doit(iterable){
var unique = []
unique[0]=iterable[0]
for(var i=1; i< iterable.length; i++){
if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
alert(doit(word))
for loop will not fail because unique.length is dynamic, i.e will change with addition of new elements to array.
Tested in Internet Explorer too.
Here is the link to jsfiddle: https://jsfiddle.net/kannanore/z5gbee55/
var str = "hhhhheeeelllloooooohhheeeyyy";
var strLen = str.length;
var newStr = "";
for(var i=0; i < strLen; i++ ){
var chr$ = str.charAt(i);
//if(i==0) {newStr = chr$ };
if(chr$ == str.charAt(i+1)){
strLen = str.length;`enter code here`
}else{
newStr = newStr + chr$ ;
}
}
//document.write(newStr);
console.log(newStr);
//Answer: helohey

How do I print a list of elements in array in JavaScript?

I'm very new to JavaScript and am trying to solve this challenge. I want to print out "A" on the first line, then "AB" on the second, then "ABC" on the third, until I print out "A....Z". Also, when I get to E, I want to replace it with 3. So far, I have created an array containing all the letters. I started with a for loop, but haven't gotten far. Any help would be appreciated!
Here you are:
var array = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
for (var i = 0; i < array.length; i++) {
var str = '';
for (var j = 0; j <= i; j++) {
if (array[j] == 'E') str += '3';
else str += array[j];
}
document.querySelector('span').innerHTML = document.querySelector('span').innerHTML + str + '<br />';
}
<span></span>
Hope this helps.
Go simple in the first draft. Save all the alphabets in an array. Use for loop to print. And print "3" for every fifth looping.
If your array is named ar then i think you can do this
for(var i = 0;i<ar.length;i++){
for(var j = 0;j<=i;j++){
if(ar[j]==='E')
ar[j]='3';
console.info("---->>"+ar[j]);
}
console.log("");
}

Categories