indexOf ignores second character in array - javascript

I'm just studying JS and I need to write a program that checkes if the string in the first element of the array contains all of the letters of the string in the second element of the array.
I've made a code like this:
function mutation(arr) {mutation: {
var lowerCaseStringOne = arr[0].toLowerCase();
var lowerCaseStringTwo = arr[1].toLowerCase();
if (lowerCaseStringOne === lowerCaseStringTwo) {
console.log(true);
break mutation;
}
var newArray = [];
for (var i = 0; i < lowerCaseStringTwo.length; i++){
console.log(lowerCaseStringTwo[i]);
if (lowerCaseStringTwo.indexOf(lowerCaseStringOne[i]) > 0) {
newArray.push(lowerCaseStringTwo[i]);
console.log('---');
}
}
var result = newArray.join("");
if (result === lowerCaseStringTwo) {
console.log(true);
} else {
console.log(false);
}
}
}
mutation(["Mary", "Aarmy"]);
I think it's very complicated, but I can't solve the problem - the "indexOf" function seems to ignore a second character in my loop - loggs it in the console but doesn't pushes into an array. I thought it could happen because first and second letters are similar, but it's not. No matter what letter, it just ignores it.

indexOf() will return 0 for the letter "a" in your example as the first instance is at position 0 in the array.
You should be using ">= 0"

Related

Splice method don't properly

My splice method don't work here (don't give my code attention just I want to know why this code don't work in my console).
function capSpace(txt) {
// write your code here
wordSplit = txt.split("");
for (let i = 0; i < wordSplit.length; i++) {
if (wordSplit[i].toUpperCase() == wordSplit[i]) {
wordSplit.splice(5, 0, " ")
}
}
return wordSplit
}
console.log(capSpace("fausJkalMalkihkLhb"));
First of all, you need to increment the i for each character that you add to the array.
I assume you're trying to add a space before each capital letter, in which case you need to add it at the i index, not the 5th index.
function capSpace(txt) {
// write your code here
wordSplit = txt.split("");
for (let i = 0; i < wordSplit.length; i++) {
if (wordSplit[i].toUpperCase() == wordSplit[i]) {
wordSplit.splice(i, 0, " ");
i++;
}
}
return wordSplit
}
var result = capSpace("fausJkalMalkihkLhb").join('');
console.log(result);
The splice method is adding an empty space to the wordSplit array in your snippet found here:
wordSplit.splice(5, 0, " ")
This is incrementing the length of wordSplit on each iteration and the condition of the for loop:
i < wordSplit.length
will never be satisfied because the length of wordSplit increases which creates an infinite loop and therefore is never able to return wordSplit and therefore never able to console.log the variable of result because it's stuck in an infinite loop.

How to find the missing next character in the array?

I have an array of characters like this:
['a','b','c','d','f']
['O','Q','R','S']
If we see that, there is one letter is missing from each of the arrays. First one has e missing and the second one has P missing. Care to be taken for the case of the character as well. So, if I have a huge Object which has all the letters in order, and check them for the next ones, and compare?
I am totally confused on what approach to follow! This is what I have got till now:
var chars = ("abcdefghijklmnopqrstuvwxyz"+"abcdefghijklmnopqrstuvwxyz".toUpperCase()).split("");
So this gives me with:
["a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
Which is awesome. Now my question is, how do I like check for the missing character in the range? Some kind of forward lookup?
I tried something like this:
Find the indexOf starting value in the source array.
Compare it with each of them.
If the comparison failed, return the one from the original array?
I think that a much better way is to check for each element in your array if the next element is the next char:
function checkMissingChar(ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) == ar[i-1].charCodeAt(0)+1) {
// console.log('all good');
} else {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(checkMissingChar(a));
console.log(checkMissingChar(b));
Not that I start to check the array with the second item because I compare it to the item before (the first in the Array).
Forward Look-Ahead or Negative Look-Ahead: Well, my solution would be some kind of that. So, if you see this, what I would do is, I'll keep track of them using the Character's Code using charCodeAt, instead of the array.
function findMissingLetter(array) {
var ords = array.map(function (v) {
return v.charCodeAt(0);
});
var prevOrd = "p";
for (var i = 0; i < ords.length; i++) {
if (prevOrd == "p") {
prevOrd = ords[i];
continue;
}
if (prevOrd + 1 != ords[i]) {
return String.fromCharCode(ords[i] - 1);
}
prevOrd = ords[i];
}
}
console.log(findMissingLetter(['a','b','c','d','f']));
console.log(findMissingLetter(['O','Q','R','S']));
Since I come from a PHP background, I use some PHP related terms like ordinal, etc. In PHP, you can get the charCode using the ord().
As Dekel's answer is better than mine, I'll try to propose somewhat more better answer:
function findMissingLetter (ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) != ar[i-1].charCodeAt(0)+1) {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(findMissingLetter(a));
console.log(findMissingLetter(b));
Shorter and Sweet.

How to count vowels in a Javascript string with two functions?

I'm trying to write a Javascript function that counts the vowels in a string by calling another function inside that function, but when I test it in the console it returns 0.
Here is my first function that works fine and recognizes if a string is a vowel:
function isVowel(ch){
var pattern = /[aeiouAEIOU]/
return pattern.test(ch);
};
For the second function none of my ideas have worked. Here are a few examples of what I have tried so far:
This one returns me a 0:
function countVowels(str){
var count = 0;
for(var i; i <= str.length; ++i){
if(isVowel(i)){
++count;
}
}
return count;
};
I also tried the above, but removing the .length after str in the for() area.
Another example, but this one gives me an error:
function countVowels(str){
var count = 0
var pattern = /[aeiouAEIOU]/
for(var i = 1; i <= str.length(pattern); ++i){
if(isVowel(i)){
++count;
}
}
return count;
};
I've tried various other functions as well, but for the sake of keeping this post relatively short I won't continue to post them. I'm quite new to Javascript and I'm not sure what I'm doing wrong. Any help would be greatly appreciated!
Try using .match() with the g attribute on your String.
g: global
i: case insensitive
Regexp documentation
function countVowels(ch){
return ch.match(/[aeiouy]/gi).length;
}
var str = "My string";
alert(countVowels(str)); // 2
Although Robiseb answer is the way to go, I want to let you know why you code is not working (I'm referring your first attempt). Basically you made two mistakes in the loop:
As CBroe stated, you are passing i to your isVowel function. i is a integer representing the index of the loop, not the actual character inside the string. To get the character you can do str.substr(i, 1), what means "give me one character from the position i inside the string".
You are not giving a initial value to the i variable. When you create a variable, it is undefined, so you can not increment it.
alert(countVowels("hello"));
function countVowels(str) {
var count = 0;
for (var i = 0; i <= str.length; ++i) {
if (isVowel(str.substr(i, 1))) {
count++;
}
}
return count;
};
function isVowel(ch) {
var pattern = /[aeiouAEIOU]/
return pattern.test(ch);
};
UPDATE: You will see that other answers use other methods to select the character inside the string from the index. You actually have a bunch of different options. Just for reference:
str.slice(i,i+1);
str.substring(i,i+1);
str.substr(i,1));
str.charAt(i);
str[i];
i is the index, not the character. It should be:
if (isVowel(str[i])) {
count++;
}
Also, str.length(pattern) is wrong. length is a property, not a function, so it should just be str.length.
You forgot to assign the value 0 to i variable
And parameter for isVowel is the character, not the index of string
Here information about the JS language: https://stackoverflow.com/tags/javascript/info
function isVowel(ch){
var pattern = /[aeiouAEIOU]/
return pattern.test(ch);
}
function countVowels(str){
var count = 0;
// you forgot to assign the value to i variable
for(var i = 0; i < str.length; i++){
// isVowel(str[i]), not isVowel(i)
if(isVowel(str[i])){
count++;
}
}
return count;
}
console.log(countVowels('forgot'))
Obviously you should do it this way:
function isVowel(c){
var lc = c.toLowerCase();
if(lc === 'y'){
return (Math.floor(Math.random() * 2) == 0);
}
return ['a','e','i','o','u'].indexOf(lc) > -1;
}
function countVowels(s){
var i = 0;
s.split('').each(function(c){
if(isVowel(c)){
i++;
}
});
return i;
}
console.log(countVowels("the quick brown fox jumps over the lazy dog"));
Which, although less efficient and less useful than other answers, at least has the entertaining property of returning a different count 50% of the time, because sometimes Y.

trouble with Javascript while loop, what am I doing wrong?

So I am doing a an exercise in which I have to sort a given string. Each word in the string contains a number in it(written like this 'H3llo'). The number that is in each word of the string should be placed in order according to the number in the new string that is to be returned.
For example if my input is "is2 Thi1s T4est 3a", then my function should return "Thi1s is2 3a T4est".
I almost cracked it but my output is incomplete. Here is my code:
function order(words) {
var lst = words.split(' ');
var count = 0;
var n = count + 1;
var s_n = n.toString();
var new_l = [];
while (count < lst.length) {
if (lst[count].includes(s_n) === true) {
new_l.push(lst[count])
}
count++
}
return new_l.join(' ');
}
When I test it, instead of getting:
console.log(order("is2 Thi1s T4est 3a"));
>>> 'Thi1s is2 3a T4est'
I get this:
console.log(order("is2 Thi1s T4est 3a"));
>>> 'Thi1s'
Can anyone explain to me what I am doing wrong?
You will basically need two loops - one for your current counter count i.e. the incremental number and another to iterate over the list of words to match that number. You increase the count only after you have finished iterating over the list.
function order(words) {
var lst = words.split(' ');
var count = 0;
var new_l = [];
while (count <= lst.length) {
for (i = 0; i < lst.length; i++) {
if (lst[i].includes(count)) {
new_l.push(lst[i])
}
}
count++;
}
return new_l.join(' ');
}
console.log(order("is2 Thi1s T4est 3a"));
Notice too that you don't need s_n -- the conversion is implicit, and you don't need === true as this is implicit in the if statement.
The main thing you are doing wrong is that you assign s_n to the string '1' before your loop, but you never update it within the loop. At the same time as you update count, you need to update s_n to the string of the next integer.
So you 'fixed' the part where you weren't updating the value of n or s_n within your outer loop, but the code still wont't work because you are now using count both to increment the digit you are looking for (within a word) and to increment the search through the list of words. You need an inner loop (and another variable) to increment the search.

match two elements in an array with a single for loop

I have the following code:
var fl = myitems(); //grabs all items (an array)
var f1 = f2 = new String();
function myfunc(){
//find two items in an array and load vars
for(i=0; i<fl.length-1; i++){
if(fl[i] == "match1"){
f1 = fl[i];
}
}
for(i=0; i<fl.length-1; i++){
if(fl[i] == "match2"){
f2 = fl[i];
}
}
}
I'd like to avoid the extra for(), if possible. I try else if, but many times the first match element is caught after the 2nd element has already been surpassed in the for loop.
I'm sure there is an easy way out of this (else if, and else don't seem to do the trick).
Can anyone tell me what common practice is here?
You can do both tests in the same loop:
for (i = 0; i < fl.length - 1; i++) {
if (fl[i] == "match1") {
f1 = fl[i];
} else if (fl[i] == "match2") {
f2 = fl[i];
}
}
Note that the comparison operator is ==, not =.
I know that this does not answer the original question, but it looks like you are trying to find out whether the arrays contain 'match1' and 'match2', you can do that with Array.prototype.indexOf:
var items = myitems();
if(items.indexOf('match1') !== -1) {
// Do whatever you need to do if the array contains 'match1'
}

Categories

Resources