Reputation: 199
I'm trying to do a little program to reverse a string and I'm using this approch:
var reverse = (str) => {
let returned = [...str];
for(let i = 0; i < returned.length; i++)
{
let symetrical = returned.length - i - 1;
let temp = returned[i];
returned[i] = returned[symetrical];
returned[symetrical] = temp;
}
return returned.join("");
}
but when i test the function like reverse('123')
I got the same input as result?
why the returned
variable didn't change?
Upvotes: 0
Views: 43
Reputation: 12209
You can simplify the function by creating two arrays, the array of the letters of the param str, and the results array which takes the length - 1 - i
algorithm you had:
let reverse = (str) => {
const arr1 = [...str];
const arr2 = []
for(let i = 0; i < arr1.length; i++)
{
arr2[i] = arr1[arr1.length - 1 - i];
}
return arr2.join("");
}
console.log(reverse("abcde"));
Upvotes: 1