This question already has answers here:
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
(10 answers)
How do you reverse a string in-place in JavaScript?
(57 answers)
Closed 3 years ago.
Learning JavaScript and doing some questions. I am trying to reverse a given string and I don't know why my logic is wrong as running through the debugger it looks like it's doing the swapping as intended.
Any help is really appreciated, I know it's simple but that means I'm missing something important.
function reverse(s) {
let i = 0;
let j = s.length - 1;
while (i < j) {
let temp = s[j];
s[j] = s[i];
s[i] = temp;
i++;
j--;
}
return s;
}
console.log(reverse("hello"));
Since strings are immutable, you can split the string with empty string to make an array and join them before returning:
function reverse(s) {
s = s.split(''); // split here
let i = 0;
let j = s.length - 1;
while (i < j) {
let temp = s[j];
s[j] = s[i];
s[i] = temp;
i++;
j--;
}
return s.join(''); // join and return
}
console.log(reverse("hello"));
function reverse(word) {
let wordArray = word.split('');
wordArray.reverse();
return wordArray.join('');
}
console.log(reverse("hello"));
Related
Trying to return the highest 5 digit number out of any given number i.e 34858299999234
will return 99999
I think I have it narrowed down to the for loop not iterating the array properly OR the values for 'hold1' and 'hold2' are not updating.
function solution(digits){
//Convert string to array to iterate through
let arr = digits.split("");
let final = 0;
//iterate through the array in 5 sequence steps
for(let i = 0; i < arr.length-1; i++){
let hold1 = arr[i] + arr[i+1] + arr[i+2] + arr[i+3] + arr[i+4];
hold1 = parseInt(hold1,10); //converting string to int so if statement functions correctly
let hold2 = arr[i+1] + arr[i+2]+ arr[i+3] + arr[i+4] + arr[i+5];
hold2 = parseInt(hold2,10);
if(hold1 >= hold2){
final = hold1;
}else{
final = hold2;
}
return final;
}
}
if you need a five digits result you need to change the for loop in something like this:
for (let i = 0; i < arr.length - 5; i++) {
Otherwise you will generate results shorter than 5 digits.
Also, I think you are missing the Math.max method that will compare two numbers to return the bigger one.
I rewrote your function this way:
function solution(digits) {
let op = 0;
let length = 5;
let stringDigits = String(digits); /// <-- I use string instead of array
if (stringDigits.length <= length) {
return digits; /// <-- If input is shorter than 5 digits
}
for (let i = 0; i < stringDigits.length - length; i++) {
const fiveDigitsValue = stringDigits.substr(i, length);
op = Math.max(op, Number(fiveDigitsValue));
}
return op;
}
This question already has answers here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Why is using "for...in" for array iteration a bad idea?
(28 answers)
Closed 1 year ago.
I was solving basic algorithm problems, and I got stuck in this code.
The problem was to get string data and remove duplicated charactors.
For instance, input: 'ksekkset', output: 'kset'
And this is my solution.
function solution(s) {
let answer = "";
for(let i in s) {
if(s.indexOf(s[i]) == i) answer+=s[i];
}
return answer;
}
My question is, why do I get correct answer only when I put '==' inside if()?
When I put '===' why if() only returns false?
If I use for loop, '===' also works..
function solution2(s) {
let answer = "";
for(let i=0; i<s.length; i++) {
if(s.indexOf(s[i])===i) answer+=s[i];
}
return answer;
}
I'm so confused!
As #VLAZ mentioned above.. the == vs === isn't the only difference.
I wrote changed around your program to try all combinations of the for/in change and === change, and you can see that the only one that doesn't work as expected is === with for/in.
Strange that for a string, for/in gives you the indices as strings even though they are the numbers!
const s = "stackoverflow"; // repeated 'o' makes answer interesting
const answers = {
answerForInTripple: "",
answerForInDouble: "",
answerForTripple: "",
answerForDouble: "",
};
for(let i in s) {
if(s.indexOf(s[i]) == i) {
answers.answerForInDouble += s[i];
}
if(s.indexOf(s[i]) === i) {
answers.answerForInTripple += s[i];
}
}
for(let i=0; i < s.length; i++) {
if(s.indexOf(s[i]) == i) {
answers.answerForDouble += s[i];
}
if(s.indexOf(s[i]) === i) {
answers.answerForTripple += s[i];
}
}
console.log(answers);
console.log('here is the difference between what you are comparing');
for(let i in s) {
const idx = s.indexOf(s[i]);
console.log(typeof i, i, typeof idx, idx);
}
console.log('simpler example');
for (let i in 'test') console.log(typeof i, i);
This question already has answers here:
JavaScript function to automatically count consecutive letters in a string
(5 answers)
Closed 1 year ago.
I am a beginner in javascript, I want to get a count of repeated values on an array
I have a string "aaaaaabbbbbbbcccccccaa" and I want the output array be like ["a6", "b7", "c7", "a2"];
I tied but failed. Please help me out
Thanks In Advance :)
var a = "aaaaaabbbbbbbcccccccaa";
function aa(data){
var a = [];
var x = [];
//var b = data.split("")
// var b = data.split("").filter((val,key, arr)=>{
// //console.log(arr.indexOf(val) +" "+ key )
// return arr.indexOf(val) === key
// })
//console.log(b);
for(let i = 0; i<= data.length-1; i++){
for(let j = 0; j<= data.length-1; j++){
if(data[i] !== data[j] && x.indexOf(data[i]+""+j) <0){
x.push(data[i]+""+j);
a.push(data[i] +""+ j);
break;
}
}
}
console.log(x);
return a;
}
console.log(aa(a));
I'd use a regular expression to match repeated characters in the string, then map them to match[0] + match.length to get the concatenated substring for that portion:
const aa = data => data
.match(/(.)\1*/g)
.map(match => match[0] + match.length);
console.log(aa('aaaaaabbbbbbbcccccccaa'));
If you don't want to use a regular expression, don't use a nested loop like that from 0 to the string length - instead, count up repeated characters from inside the first loop, starting at the current i index and incrementing it:
function aa(data) {
const result = [];
for (let i = 0; i < data.length; i++) {
const char = data[i];
let matches = 1;
while (data[i + 1] === char) {
i++;
matches++;
}
result.push(char + matches);
}
return result;
}
console.log(aa('aaaaaabbbbbbbcccccccaa'));
I need help... I'm learning JavaScript, and it seems easy, but I may just be overlooking... everything... My problem is I need to return a string of all the even numbers between 0 and num inclusive; ex 7 gets you 0246, etc. I've gotten:
function stringOfEvens(num) {
for (let i = 0; i <= num.length; ++i) {
if (i % 2 === 0 ); {
return i;
}
}
}
I know the whole outlook is to run a for loop that goes from 0 to the number in question appending each time and if that number % 2 = 0, return that number, but something is a miss... I may even be overthinking and approaching this whole thing wrong... It is figuratively driving me mad...
function theJob(limit) {
var res = ''; //initialize as a string so that the other numbers will be appended instead of added
for (i = 0; i <= limit; i += 2) { // step increase by 2 to skip odd numbers
res += i;
}
return res; // returning the resulting string
}
console.log(theJob(10));
You can do this without using the modular function, by simply starting the loop at zero and incrementing by 2 each time the loop iterates...
function stringOfEvens(num) {
var result = "";
for (let i = 0; i <= num; i += 2) {
result += i; // append this even number to the result string
}
return result;
}
console.log(stringOfEvens(10));
You're returning the first number you find. a better approach would be to build the string in the loop then return after that string after the loop. Also no need for num.length if num is an int.
function stringOfEvens(num) {
var stringToReturn = "";
for (let i = 0; i <= num; i++) {
if (i % 2 === 0) {
stringToReturn = stringToReturn + i;
}
}
return stringToReturn;
}
function stringOfEvens(num) {
var str= ' ';
for(var i = 0; i <= num; i = i + 2){
str += i;
}
return str;
}
console.log(stringOfEvens(10))
Just for fun, since it's not particularly efficient:
const stringOfEvens = n => Array(~~(n/2)+1).fill().map((_, i) => 2*i).join("")
or annotated:
const stringOfEvens = n => // arrow function definition, returning:
Array(~~(n / 2) +1) // a sparse array of the required length
.fill() // made unsparse, so .map works
.map((_, i) => 2 * i) // then containing the even numbers
.join("") // and converted to a string
or alternatively (and more efficiently) using Array.from which can call an explicit map function in place:
const stringOfEvens = n => Array.from(Array(~~(n/2)+1), (_, i) => 2*i).join("")
Actually I found an answer a few minutes ago.
But I found something strange.
This is my answer for 'Missing letters' in freeCodeCamp challenges.
function fearNotLetter(str) {
var string;
for (i=0;i<str.length;i++) {
if(str.charCodeAt(i)+1 < str.charCodeAt(i+1)){
string = String.fromCharCode(str.charCodeAt(i)+1);
}
}
return string;
}
When I change < operator in if statement into != (not same), it doesn't work!
For me, it seems that != works exactly same as < operator does.
(Because 'not same' can mean something is bigger than the other.)
What is the difference between < and != in the code above?
Your code has a small defect that works when you use < but not !=.
If you see str.charCodeAt(i+1); this code is checking one spot past the end of the string on the last iteration and will return a NaN result.
If I provide the string "abce" it will check if f is < NaN. I believe NaN can't be compared to f's value so it doesn't go into the if statement. So it will keep the missing letter d that was found in the previous iterations which is stored in your string variable.
However, if you provide the !=, then with the same scenario it knows f != NaN and goes into the if statement. This then overwrite the actual missing letter and fails your FCC test case because it is replacing the missing d with f in your string variable.
To fix your code, simply change the for loop to end one iteration before the length of the string.
for (i = 0; i != str.length-1; i++) {
}
This is my method without using .charCodeAt() function :)
function fearNotLetter(str) {
var ind;
var final = [];
var alf =['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'];
str = str.split('');
ind = alf.splice(alf.indexOf(str[0]),alf.indexOf(str[str.length-1]));
for(var i=0;i<ind.length;i++){
if(str.indexOf(ind[i]) == -1){
final.push(ind[i]);
}
}
if(final.length != 0){
return final.join('');
}
return;
}
fearNotLetter("bcef");
My solution:
function fearNoLetter(str){
var j= str.charCodeAt(0);
for(var i=str.charCodeAt(0); i<str.charCodeAt(str.length-1); i++){
j = str.charCodeAt(i - str.charCodeAt(0));
if (i != j){
return String.fromCharCode(i);
}
}
}
My solution:
function fearNotLetter(str) {
let y = 0;
for (let i = str.charCodeAt(0); i < str.charCodeAt(str.length - 1); i++) {
if (str.charCodeAt(y) != i) {
return String.fromCharCode(i);
}
y++;
}
return;
}
console.log(fearNotLetter("ace"));
function fearNotLetter(str) {
let alpha = "abcdefghijklmnopqrstuvwxyz";
let alphabet = []
for(let j = 0; j< alpha.length; j++){
alphabet.push(alpha[j])
}
if (alphabet.length == str.length){
let result = undefined;
return result
}else{
const start =alphabet.indexOf(str[0])
let end = (str.length)-1
const stop = alphabet.indexOf(str[end])
const finish = alphabet.slice(start,stop)
let result = finish.filter(item => !finish.includes(item) || !str.includes(item))
result = String(result)
return result
}
return result
}
console.log(fearNotLetter("abcdefghijklmnopqrstuvwxyz"));