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"));
This question already has answers here:
Is there a better way of writing v = (v == 0 ? 1 : 0); [closed]
(31 answers)
Closed 4 years ago.
I have a for loop and inside I'd like to get a sequence like 1,-1,1,-1...
(The loop does other things also so I don't want to alter the loop itself)
For now I have a solution like below, but there must be some more elegant way to do this I think :)
let plusMinus = [-1, 1]
for (let i = 0; i < 10; i++) {
console.log(plusMinus[i % 2])
}
let state = 1;
for (let i = 0; i < 10; i++)
console.log(state = -state)
Use Array.from :
var length = 5;
var sequence = Array.from(Array(length), (x, i) => i % 2 ? -1 : 1);
console.log(sequence);
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"));
Im working with this challenge question and I am struggling with the number count. I can get it work to return the position in the string, but not the actual letter count. Any help is appreciated.
Question -
Write a function named letterCount that takes a string and returns an
object with the letters and the number of their occurrences.
My Code so far -
var stringCount = "Hello";
function letterCount(string) {
var stringObject = {};
for (var i = 0; i < string.length; i++) {
stringObject[string[i]] = [i];
}
return stringObject;
}
letterCount(stringCount);
You have done almost everything right, only problem is the assignment part, which you need to do this way:
var stringCount = "Hello";
function letterCount(string) {
var stringObject = {};
for (var i = 0; i < string.length; i++) {
stringObject[string[i]] = ((stringObject[string[i]]) ? stringObject[string[i]] : 0) + 1;
}
return stringObject;
}
console.log(letterCount(stringCount));
So technically, what happens in the line:
stringObject[string[i]] = ((stringObject[string[i]]) ? stringObject[string[i]] : 0) + 1;
The program checks if that particular index exists in the object.
If it doesn't exists (not defined, undefined), it assigns 0.
If it exists, it takes the same value.
It adds 1 to the above value.
The same above line can be written this way:
// Check if the current key exists.
if (typeof stringObject[string[i]] == "undefined") {
// If it doesn't, initialise it 1.
stringObject[string[i]] = 1;
} else {
// If it exists, increment it.
stringObject[string[i]] = stringObject[string[i]] + 1;
// Another way:
// stringObject[string[i]]++;
}
This question already has an answer here:
Why is the loop assigning a reference of the last index element to? [duplicate]
(1 answer)
Closed 8 years ago.
Can someone please tell me how can I grab i properly? By now, it's just displaying the same number (the value of a.length when clicking on any anchor element.
var a = document.getElementsByTagName('a');
for (i = 0, j = a.length; i< j;i++) {
a[i].onclick = function() {
console.log(i); //display a.length in all anchors
return false;
}
}
var a = document.getElementsByTagName('a');
for (i = 0, j = a.length; i< j;i++) {
a[i].idx = i;
a[i].onclick = function() {
console.log(this.idx);
return false;
}
}