0

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?

5
  • 1
    Did you step through it in a debugger? Commented Oct 28, 2022 at 22:37
  • Tip: JavaScript swapping isn't this hard. [ r[a], r[b] ] = [ r[b], r[a] ] Commented Oct 28, 2022 at 22:40
  • 3
    There's also str.split('').reverse().join('') Commented Oct 28, 2022 at 22:46
  • 1
    The problem is that your loop is swapping each pair of elements twice. This is a common mistake in exercises like this. Change the loop to stop at the halfway point of the array. Commented Oct 28, 2022 at 22:51
  • @Barmar Yes That was the issue , thanks y'all Commented Oct 28, 2022 at 22:53

1 Answer 1

1

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"));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.