I am trying to run below code and expecting 14 on console but I am getting nothing, I don't know why, can any one please tell me.
let array = ['O','Q','R','S'];
let missingLetter = '';
let isUpperCase = false;
const engAlphabets = ['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'];
// Find 1st letter index in the engAlphabets array
const arrayFirstLetter = array[0].toLowerCase();
const firstIndex = engAlphabets.indexOf(arrayFirstLetter);
// Find the missing letter in the array
let j=0;
for(let i=firstIndex; i<array.length; i++) {
console.log(i); // it should be 14 but, there is nothing on console.
let arrayInputLetter = array[j].toLowerCase();
j += 1;
if(engAlphabets[i] !== arrayInputLetter) {
missingLetter = engAlphabets[i];
break;
}
}
First of all, the for-loop isn't even entered, because i is less than array.length from the start, as deceze♦ and zhulien pointed out in the comments. If I understand your goal, you would want i to be 0 in the beginning, so the for-loop iterates over array.
Then it also seems like you sometimes unintentionally swapped i and j in the end. As you can see, j isn't even needed...
And the boolean isUpperCase isn't used after being initialized, so you can just remove it from your code.
let array = ['O','Q','R','S'];
let missingLetter = '';
const engAlphabets = ['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'];
const arrayFirstLetter = array[0].toLowerCase();
const firstIndex = engAlphabets.indexOf(arrayFirstLetter);
for (let i = 0; i < array.length; i++) {
let arrayInputLetter = array[i].toLowerCase();
if (engAlphabets[firstIndex + i] !== arrayInputLetter) {
missingLetter = engAlphabets[firstIndex + i];
break;
}
}
console.log(missingLetter);
In your for, i start with 14 (firstIndex) and increasing while lower than 4 (array.length). So codes inside the for block do not run.
Related
I've been trying to use a for loop to make a code that alternates between two strings and ends with .toUpperCase , but I'm completely stuck. I'm "able" to do it with an array with two strings (and even so it has a mistake, as it ends with the first string of the array...), but not with two separate constants.
Could anyone offer some help?
function repeteFrases(num) {
const frases = ["frase um", "frase dois"];
let result = "";
for (let i = 0; i < num; i++) {
result += i === num - 1 ? frases[0].toUpperCase() : `${frases[0]}, ${frases[1]}, `;
}
return result;
}
console.log(repeteFrases(2));
In order to alternate between two states you can use the parity of the index, i.e., the condition would be i % 2 == 0, like this:
function repeteFrases(num) {
const frases = ["frase um", "frase dois"];
let result = "";
for (let i = 0; i < num; i++) {
result += i % 2 == 0 ? frases[0].toUpperCase() : `${frases[0]}, ${frases[1]}, `;
}
return result;
}
console.log(repeteFrases(5));
You've almost got it.. I think what you're asking for is to repeat phrase one or two (alternating), and for the last version to be uppercase. I notice someone else made your code executable, so I might be misunderstanding. We can test odd/even using the modulus operator (%), which keeps the access of frases to either the 0 or 1 position. The other trick is to loop until one less phrase than needed, and append the last one as upper case.
function repeteFrases(num) {
const frases = ["frase um", "frase dois"];
//Only loop to 1 less than the expected number of phrases
const n=num-1;
let result = "";
for (let i = 0; i < n; i++) {
//Note %2 means the result can only be 0 or 1
//Note ', ' is a guess at inter-phrase padding
result+=frases[i%2] + ', ';
}
//Append last as upper case
return result+frases[n%2].toUpperCase();
}
console.log(repeteFrases(2));
console.log(repeteFrases(3));
Use frases[i % frases.length] to alternate the phrases (however many there might be)
function repeteFrases(num) {
const frases = ["frase um", "frase dois"];
let result = "";
for (let i = 0; i < num; i++) {
const next = frases[i % frases.length];
const isLast = (i === num - 1);
result += isLast ? next.toUpperCase() : `${next}, `;
}
return result;
}
console.log(repeteFrases(5));
I'm trying to build a JavaScript devowelizer, but I'm producing an infinite loop.
I'm hoping someone on Stack Overflow can help?
The code =>
let userWord = prompt("Type a word to devowelize: ");
userWord = Devowelize(userWord);
alert(userWord);
function Devowelize(word) {
for (let i = 0; i <= word.length; i++) {
let eatChars = "aeiou"
for (let i2 = 0; i2 <= eatChars.length;) {
if (word[i] == eatChars[i2] &&
word[i] != "") {
word = word.replace(word[i], "");
} else {
i2++;
}
}
}
return word
}
You are using here for (let i = 0; i <= word.length; i++) this part i <= word.length isn't correct because you will try to access the array word using the i index after that in your code so in the last iteration you will access an index which is not defined by your array the last index of an array in javascript is always arrayLength-1 if you access an item which is out of the array you will get an undefined as value which will generates an infinte loop in your case you have done the same thing here for (let i2 = 0; i2 <= eatChars.length;) but the first loop is the responsible of the infinite loop in your code
Your solution is almost there, but you're trying to solve this problem in a very roundabout way. Let's make it a bit easier to understand.
In JavaScript, you can easily check if a string contains another string. For example, if we wanted to check if a character was in a string, we could do this:
let eatChars = "aeiou"
eatChars.includes('e') === true
So knowing that we can do that in a single statement, let's reuse some of the code you've got and substitute the character 'e' for the characters in your word.
let outWord = ""
const eatChars = "aeiou"
// '<= word.length' becomes this, because the string positions only go up to 'word.length - 1
for (let i = 0; i < word.length; i++) {
if (!eatChars.includes(word[i])) { // so the character isn't a vowel
outWord += word[i]
}
}
return outWord
The comments mention learning about 'map' and 'filter'. I'd recommend using a reducer for this if you wanted to be fancy! You could try something like this:
const devowel = (word) => Array.from(word).reduce((out, currentCharacter) => ...)
I need very specific answer to this particular HackerRank problem : https://www.hackerrank.com/challenges/plus-minus/problem.
Why this code is passing all the test-cases ?
function plusMinus(arr) {
let positives = 0
let negatives = 0
let zeros = 0
const length=arr.length
for (var i = 0; i < arr.length;i++){
if (arr[i] > 0) {
positives++
} else if (arr[i] < 0) {
negatives++
} else {
zeros ++
}
}
const positiveRatio = Number(positives / length).toFixed(6)
const negativeRatio = Number(negatives / length).toFixed(6)
const zeroRatio = Number(zeros / length).toFixed(6)
console.log(positiveRatio)
console.log(negativeRatio)
console.log(zeroRatio)
}
And why this code is not passing any test-case ?
(I have edited my code: sorry for earlier wrong code) This code also does not works.
function plusMinus(arr) {
var l = arr.length;
var positiveCounter = 0;
var negativeCounter = 0;
var zeroCounter = 0;
for(var i=0; i<=l; i++) {
if (arr[i]>0) {
positiveCounter+=1;
} else if (arr[i]<0) {
negativeCounter+=1;
} else {
zeroCounter+=1;
}
}
console.log (
(positiveCounter/l).toFixed(6)+ '\n' +(negativeCounter/l).toFixed(6)+ '\n' +(zeroCounter/l).toFixed(6) );
}
I don't want alternative ways to solve this. I just want to know why the first code works and the second code doesnt ???
These 2 codes are different, you are dividing the numbers by the length twice
First in the assignment to a variable (var p= ...)
Second when doing the console.log ((p/l).toFixed(6))
Also, like mentionned by #DhananjaiPai, they have multiple console.log and you only have one with breaking characters which can be differently interpreted by OS (\r\n or \n )
You also have a something wrong in your loop, I will let you find that one but remember that an array begin from the index 0, if the array has 3 elements, that will be [0, 1, 2]
I'm working on some codewars problems and I came to this 'remove noise thing', I guess the point is to escape backslash \ and use replace method, which was easy. But I didn't want to use replace, instead I found myself in trouble trying to remove items with splice method.
Funny thing is, when I debug in Chrome dev tools, step by step I see items get removed, but console.log spits out certain characters($/·|ªl) problematic to remove, and at the end gets returned and join with those characters. Why is that?
function removeNoise(str) {
var base = "%$&/#·#|º\ª";
var arr = str.split('');
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
var condition = base.indexOf(item);
if(condition + 1) {
//works like a charm
//arr[i] = '';
arr.splice(i,1);
//this thing wont work
//when debugging it removes the items from the array
//console log print no removing
}
}
return arr.join('');
}
removeNoise('he%$&/#·#|º\ª\llo'); //=> $/·|ªllo
You're using splice to remove entries from your array, but you're then incrementing i for the next loop. If you remove the entry at index 5 from a 10-entry array, what was the entry at index 6 is now at index 5 (of what's now a 9-entry array), so you don't want to increment your index.
The solution is to use a while loop and only update i if you don't splice:
function removeNoise(str) {
var base = "%$&/#·#|º\ª";
var arr = str.split('');
var i = 0;
while (i < arr.length) {
var item = arr[i];
var condition = base.indexOf(item);
if (condition + 1) {
// Remove this entry, reuse same value for 'i'
arr.splice(i,1);
} else {
// Don't remove this entry, move to next
++i;
}
}
return arr.join('');
}
var result = removeNoise('he%$&/#·#|º\ª\llo');
var pre = document.createElement('pre');
pre.appendChild(
document.createTextNode(result)
);
document.body.appendChild(pre);
You're removing characters from your array. This will throw your indexer variable i out of sync with the characters you want to test. Easy way to fix is to start at the end of the array working your way to the beginning.
Change your for loop to this.
for(var i = arr.length -; i <= 0; i--) {
function removeNoise(str) {
var base = "%$&/#·#|º\ª";
var arr = str.split('');
for(var i = arr.length - 1; i <= 0 ; i--) {
var item = arr[i];
if(base.indexOf(item) >= 0) {
//remove the offending character
arr.splice(i,1);
}
}
return arr.join('');
}
removeNoise('he%$&/#·#|º\ª\llo'); //=> $/·|ªllo
So, I have following js setup:
var NAMES = [];
function INFO(id,first,middle,last){
var newMap = {};
newMap[id] = [first, middle, last];
return newMap ;
}
Then,
for (var j = 0; j < NUMBER.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
if (NAMES[my_name] !== 185){ //Needs to check here
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}else{
}
}
alert(JSON.stringify(NAMES , null, 4));
Here is a screenshot of the alert:
I hardcoded the number "185" for this example. I need to check if the id of 185 exists, then skip to else. I am not sure how to check it. I tried typeof, undefinedetc. but no luck.
(In other words, I should only have one "185").
Any help? Thanks!
If I understood correctly what you are trying to achieve, you have to iterate over NAMES and check every element. For example, you could do it using [].some javascript function:
if (!NAMES.some(function(v){return v[my_name]})) {
...
} else {
}
If you want to remove duplication you can just use NAMES as an object instead of array like this
var all_names = [185, 185, 181],
NAMES = {};
for (var j = 0; j < all_names.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
NAMES[my_name] = ["sean","sdfsd","sdfsfd"];
}
alert(JSON.stringify(NAMES, null, 4));
First of all I would recommend making a JS Fiddle or CodePen out of this so people can see the code running.
I believe that the issue is that NAMES[my_name] is not doing what you think it is. NAMES is an Array so when you say NAMES[my_name] you are really asking for the ITEM in the array so you are getting the entire object that you create in the INFO function. What you really want is to see if the object has an attribute that matches the value (e.g. "185" from the my_names array).
This is not the prettiest code but it will show you how to do what you really want to do:
var NAMES = [];
function INFO(id,first,middle,last){
var newMap = {};
newMap[id] = [first, middle, last];
return newMap ;
}
all_names = ["185", "186", "185"]
for (var j = 0; j < all_names.length; j++) {
var my_name = all_names[j];
if (NAMES.length == 0) {
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
} else {
var match = false;
for (var x = 0; x < NAMES.length; x++) {
console.log(NAMES[x][my_name] + ' : ' + my_name);
if(NAMES[x][my_name]) {
match = true;
}
}
if (!match) {
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}
}
}
alert(JSON.stringify(NAMES , null, 4));
Note the if that looks at NAMES[x][my_name] - this is asking if the item at array index 'x' has an attribute of 'my_name' (e.g. "185"). I believe this is really what you are trying to do. As its after midnight I assure you that there is more concise and pretty JS to do this but this should show you the basic issue you have to address.
Try this code using hasOwnProperty method :
for (var j = 0; j < NUMBER.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
if (!NAMES[my_name].hasOwnProperty("185")){ //Needs to check here
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}else{
}
}