How to detect if the array is an space using loop? - javascript

Hello guys Newbie here...
I try to accept an sentence then return it without vowels
By allocating nonvowels in new array but it seems it cant detect the value of arrays and it return undefine
I think the reason was when the character is space or special character.
but i try to detect spaces but did not work
var array = "Your website is good";
var varray = ['a', 'e', 'i', 'o', 'u'];
var newarray = "";
for (let i = 0; i <= array.lenght; i++) {
if (!(array[i].toLowerCase() == 'a' || array[i].toLowerCase() == 'e' || array[i].toLowerCase() ==
'i' || array[i].toLowerCase() == 'o' || array[i].toLowerCase() == 'u')) {
newarray = newarray + array[i];
console.log(array);
}
}

First, the variable called "array" is actually a string. Also, when declaring a new variable as an empty array, you would want to do:
var newArray = [];
So I think for this, you would want to separate the string into an array of lowercased words using
var wordsArray = array.toLowerCase().split(" ");
That will split the string into an array of lowercased words, without the spaces.
Then, you could loop through that array to separate each word into its own array of characters, something like:
for (let i = 0; i < wordsArray.length; i++) {
let thisWordArray = wordsArray[i].split("");
let thisArrayHolder = [];
for (let j = 0; j < thisWordArray.length; i++) {
if (!vowelsArray.includes(thisWordArray[j]) {
thisArrayHolder.push(thisWordArray[j];
}
newArray.push(thisArrayHolder.join(""));
}
That will loop through each word, then during that loop, loop through each letter in the current word, check if that letter is a vowel (by seeing if it's in the vowelArray), then if it isn't, add it to the holder array. Then, at the end of that word, combine the letters of that holder array (which should now be an array of consonant-only letters) into a string, then add that whole string into the newArray. At the end of that, you'll have an array of words that don't have vowels. If you want to get that array back into string form, as a sentence of letters without vowels, you would need to do:
let newSentence = newArray.join(" ");

You have a number of simple mistakes:
lenght is a typo for length.
The loop condition should use < rather than <=. Array and string indexes go from 0 to length-1. That's the reason for the "undefined" error.
You have to log newarray rather than array to see the result. This is also only necessary at the end, not inside the loop.
You're not using the varray array.
var array = "Your website is good";
var varray = ['a', 'e', 'i', 'o', 'u'];
var newarray = "";
for (let i = 0; i < array.length; i++) {
if (!varray.includes(array[i].toLowerCase())) {
newarray = newarray + array[i];
}
}
console.log(newarray);
Your variable names are poorly chosen, since array and newarray are strings, not arrays.

A couple of problems with the code in the question. The misspelling of 'length' has already been pointed out. You are also testing less than or equals so at the end of the array the code is trying to get a character that doesn't exist (remember, the counting started at zero).
With these two things sorted your code is OK, but it can be made shorter by for example using the JS function includes which will use your varray - testing whether the character at position i is contained in varray or not.
var array = "Your website is good";
var varray = ['a', 'e', 'i', 'o', 'u'];
var newarray = "";
for (let i = 0; i < array.length; i++) {
if (!varray.includes(array[i].toLowerCase())) {
newarray = newarray + array[i];
}
}
console.log(newarray);

Related

Mutate one letter of a string inside an array [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 1 year ago.
I would like to understand why I can't use this construction to capitalize de first letter of my strings of the array with JavaScript.
function capitalize(array){
for (let i = 0; i < array.length; i++){
array[i][0] = array[i][0].toUpperCase()
}
return lst;
}
I have already re-writed my code, to a way it works:
function capitalize(array){
for (let i = 0; i < array.length; i++){
array[i] = array[i][0].toUpperCase() + array[i].slice(1)
}
return array;
}
But I wanted to understand more deeply why
Strings are Immutable, so you can't modify a single letter of a string and have the original change, you have to assign an entirely new string.
let str = 'Hello';
str[0] = 'G' // doesn't actually do anything, since str is immutable
console.log(str)
str = 'G' + str.slice(1) // assigns a new string to str, so it works
console.log(str)
Strings are immutable. You need to reassign the entire string.
let arr = ["this", "is", "a", "test", "string"]
function capitalize(array){
for (let i = 0; i < array.length; i++){
array[i] = array[i].replace(array[i][0], array[i][0].toUpperCase() )
}
console.log( array);
}
capitalize(arr)

.join is not a function

Newer to coding and javascript and I am trying a codewars challenge. I setup an array to repeat a letter at certain indexes of my newArray based on a loop. For example if input was: cwAt expected output should be: C-Ww-Aaa-Tttt.
Been stuck on this for several hours (and have slept on it). I get error code:
newArray.join is not a function
when I try to run this and not sure what I can do to fix this problem. I feel its something simple and I just need to learn why this is happening.
function accum(s) {
let mumble = s.split('');
for (i = 0; i < mumble.length; i++) {
let newArray = [mumble[i].toUpperCase(), ''];
for (j = i; j > 0; j--) {
newArray = newArray.push(mumble[i]);
};
// Merge the new array into a string and set it at the mumble index required
mumble[i] = newArray.join('');
};
//Return new mumble with - as spaces between elements
return mumble.join('-');
}
console.log(accum('cwAt'));
Change newArray = newArray.push(mumble[i]); to newArray.push(mumble[i]);
push returns new length of the array.
You are storing a number in newArray. Try replace the 4 line with:
let newArray[i] = [mumble[i].toUpperCase(), ''];
and the 5 line :
for (j = 0; j < 0; j++) {
and the 6:
newArray[j] = newArray.push(mumble[i]);

Function only returning first letter capitalised

I have a function that is meant to do this:
accum("abcd"); // "A-Bb-Ccc-Dddd"
accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
We can see the first "for" loop repeats each substring by it's current (index + 1). It pushes it to the array and the output would be [ 'a', 'bb', 'ccc', 'dddd' ]
It is then obvious that I need to iterate over this array and capitalise each string which I have done by the second for loop below.
The problem is when I return the array it is returning like this: [ 'A', 'B', 'C', 'D' ]
It is returning the first substring of each string but it isn't returning the rest of them.
function accum(s) {
var splitstring = s.split("")
var newarray = []
for(var i = 0; i < splitstring.length; i++) {
newarray.push(splitstring[i].repeat(i + 1))
}
for (var i = 0; i < newarray.length; i++) {
newarray[i] = newarray[i].charAt(0).toUpperCase()
}
return newarray
}
accum("abcd")
That's because you're overwriting the string with only the first character. you need to concatenate the rest of the string.
for (var i = 0; i < newarray.length; i++) {
newarray[i] = newarray[i].charAt(0).toUpperCase() + newarray[i].slice(1);
}
Here's a shorter version of your code:
function accum(s) {
return s.split("").map((ss, i) => ss.toUpperCase() + ss.repeat(i)).join("-");
}
console.log(accum("abcd"));
It also adds the separator that you seem to want. If you actually wanted the array, then remove .join("-").
No need to use second for loop. Just use map() on the returned array.
function accum(s) {
var splitstring = s.split("");
var newarray = [];
for(var i= 0; i < splitstring.length; i++) {
newarray.push(splitstring[i].repeat(i + 1))
}
return newarray.map(j=>j[0].toUpperCase()+ j.slice(1)).join('-');
}
console.log(accum("abcd"));

Function that creates an object to count unique words from a string in javascript

I'm trying to build a program that counts unique words in a string and assigns them to a key/value pair in an object. Here is what I have so far:
function count(sentence) {
var list = sentence.split(' ');
var words = {};
for(var i = 0; i < list.length; i++) {
for(var j = -1; j < list.length; j++) {
if(list[i] !== list[j]) {
words[list[i]] = 1;
} else {
words[list[i]] += 1;
}
}
}
return wordCount;
}
var display = count('ask a question get a question');
console.log(display);
The console is giving me:
[object Object] {
a: 1,
ask: 1,
question: 2,
get: 1
}
It's not counting one of the a's. What am I doing wrong? Couldn't find anything related with objects.
Thanks!
Your code as posted doesn't run, instead of return wordCount you should have return words.
I don't know why you initialise j to -1, it just creates an additional loop as there is no element at -1.
Your logic breaks down because you are comparing each word in the list to every other word and if it doesn't match, you set its count to 1. If it does match, you increment the count.
But the next time the word doesn't match, its value is reset to 1 even if it was previously some other value. The word "question" has a value of 2 because it's the last word and doesn't have a chance to be reset.
Your logic is fundamentally broken, so a new algorithm is required. A more common approach is to go over the words once and, as each word is encountered, if it's not already on the words object, add it and set its value to 1. If it's there already, increment the value.
E.g.
function count(sentence) {
var list = sentence.split(' ');
var words = {};
for (var i = 0; i < list.length; i++) {
if (!(words.hasOwnProperty(list[i]))) {
words[list[i]] = 0;
}
++words[list[i]];
}
return words;
}
var display = count('ask a question get a question');
console.log(display);
This uses a hasOwnProperty test as you may encounter a word that is a standard property of an object. An alternative is to use:
var words = Object.create(null);
so that the words object has no inherited properties. Combined with some more recent functionality, it can be reduced to:
function count(sentence) {
return sentence.split(' ').reduce(function(acc, word) {
acc[word]? ++acc[word] : acc[word] = 1;
return acc;
}, Object.create(null));
}
var display = count('ask a question get a question');
console.log(display);
You seem to be overcomplicating this with two loops. You only need to loop through the array of words once. If your words object has that key already, increment it. If it does not, set it to 1.
function count(sentence) {
var list = sentence.split(' ');
var words = {};
for (var i = 0; i < list.length; i++) {
if(words[list[i]]) {
words[list[i]]++;
} else {
words[list[i]] = 1;
}
}
return words;
}
var display = count('ask a question get a question');
console.log(display);
You are overcomplicating the issue. For starters, you only need a single loop through all the words. Think about if you were doing this yourself on paper, you'd only read through the sentence once to count how many instances of each letter.
As you loop through, you'd be checking to see if you have already come across that word by consulting your tally table (words.hasOwnProperty).
A better solution would be:
function count(sentence) {
var list = sentence.split(' ');
var words = {};
for(var i = 0; i < list.length; i++) {
var word = list[i];
if (words.hasOwnProperty(word)) {
words[word]++;
} else {
words[word] = 1;
}
}
return words;
}
var display = count('ask a question get a question');
console.log(display);
This gives:
{
"ask":1,
"a":2,
"question":2,
"get":1
}

Memory allocation for strings and arrays in JavaScript

First function:
concatenate string and integer into one string.
insert result string into an array.
join all array's strings into one string.
Second function does the same, but instead of concatenation, it inserts 2 strings in the array.
Question: How do you figure out what function will allocate less memory?
One more question: How many strings in memory (for each iteration) for first function we will have? For example, for 1st iteration we will have only "a0" or "a0", "a" and "0"?
function joinLetters() {
var arr = [];
for(var i = 0; i < 10000; i++) {
arr.push('a' + i);
}
return arr.join('');
}
function joinLetters2() {
var arr = [];
for(var i = 0; i < 10000; i++) {
arr.push('a');
arr.push(i.toString());
}
return arr.join('');
}
joinLetters in the inner loop makes a single push, joinLetters2 does two push instead.
So you will have in the first case arr.length = 10000, while in the second arr.length = 20000.
Definitely you can expect the second function to be more memory expensive then the first.

Categories

Resources