user2395715
user2395715

Reputation: 85

New to javascript, how to write reverse iteration?

I'm currently taking an introduction CIS class at my university and one of the projects is javascript. It is split into two unrelated parts and I was able to do the second part but I'm stuck on the first one. My professor wants me to write an iteration that will display in a reverse order whatever name I write in the prompt screen. So if I write "John Smith" it will display "htims nhoj". The issue is that I have no idea how to write it.

<html>
   <body>
      <script>
         var namIn = window.prompt("Enter name:" );  
         var namAr = namIn.split("");  
         var namArLen = namAr.length;
         document.write(namAr + "<br /> Length: " + namArLen);
     </script>
   </body>
</html>

Upvotes: 3

Views: 6951

Answers (5)

Devin B.
Devin B.

Reputation: 453

(1) A more straight forward way without built-in functions:

function reverse(str) {
    let reversed_string = "";
    for (let i = str.length - 1; i >= 0; i--) {
        reversed_string += str[i];
    }
    return reversed_string;
}

(2) Using ES2015 'for' helper function:

function reverse(str) {
    let reversed_string = "";
    for (let character of str) {
        reversed_string = character + reversed_string;
    }
    return reversed_string;
}

(3) Using ES6 syntax and ES5.1 reduce():

function reverse(str) {
    return str.split('').reduce((reversed, char) => char + reversed, '');
}

// reduce takes in 2 arguments. (1) arrow function, and (2) empty string.

Chances are, for an interview, that you will not able to use the built-in functions, especially for "reverse()".

Upvotes: 0

user1106925
user1106925

Reputation:

You can accomplish this by iterating only half the number of characters.

DEMO: http://jsfiddle.net/vgG2P/

CODE:

var name = "Bob Dylan".split("");

//                    The counters will meet in the middle.
//                    --------------+----------------------
//      first char   last char      |   inc  dec
// -------v-------------v-----------v----v----v
for(var i = 0, j = name.length-1; i < j; i++, j--) {

    var temp = name[i];  // Store the `i` char
    name[i] = name[j];   // Replace the `i` char with the `j` char
    name[j] = temp;      // Replace the `j` char with the `i` char we stored

}

console.log(name.join(""));  "nalyD boB"

EXPLANATION:

What we did was split the characters into an Array, and maintain two counters, one that increments from the first character at 0, and the other that decrements from the last character at .length - 1. Then simply swap the characters.

The iteration continues while your incrementing counter is less than your decrementing counter. Since they will meet in the middle, you'll end up incrementing only half the total length.


We can also build the halves of the result without using an Array:

DEMO: http://jsfiddle.net/vgG2P/1/

var name = "Bob Dylan";

var start = "", end = ""

for(var i = 0, j = name.length-1; i < j; i++, j--) {
    end = name.charAt(i) + end
    start += name.charAt(j)
}

if (i === j)
    start += name.charAt(i)

console.log(start + end);  "nalyD boB"

Upvotes: 1

sellmeadog
sellmeadog

Reputation: 7517

I'm assuming that your professor would not be asking you how to reverse a string if he hasn't yet introduced you to the concept of arrays and loops. Basically, a string like John Smith is just an array of characters like this:

0123456789
John Smith

Again, thinking in the sense that a string is just an array of characters, you have have 10 characters that need to be reversed. So how do you go about doing this? Well, you basically need to take the last character h from the "array" you're given and make it the first character in a new "array" you're going to create. Here's an example:

var known = 'John Smith';
var reversed = ''; // I'm making an empty string aka character array
var last = known.length - 1 // This is the index of the last character

for (var i = 0; i < known.length; i++)
{
  temp += known[last - i];
}

(You can see it working here)

So what's happening?

  • We're looping over known starting at 0 and ending at 9 (from the first character to the last)
  • During each iteration, i is incrementing from 0 - 9
  • last always has a value of 9
  • last - i will give us indexes in reverse order (9, 8, 7, ..., 0)
  • So, when i is 0, last - i is 9 and known[9] is "h"; repeat this process and you get the reversed string

Hopefully this helps explain a little better what's happening when you call reverse() on an array.

Upvotes: 0

Cody Jenkins
Cody Jenkins

Reputation: 91

There's no need to split this string into an array. Just use the charAt() function and a simple for loop.

var name = window.prompt("Enter name:");
var reverse = "";
for (var i = name.length - 1; i >=0; i--) {
    reverse += name.charAt(i);
}
console.log(reverse)

Instead of converting the string to an array first, you're just reading the characters out of the string directly.

Upvotes: 1

Jason Sperske
Jason Sperske

Reputation: 30416

Strings in JavaScript have a function called split() which turn them in to Arrays. Arrays in JavaScript have a function called reverse() which reverse their order, and a function called join() which turn them back into Strings. You can combine these into:

"John Smith".split("").reverse().join("")

This returns:

"htimS nhoJ"

Also, and I don't know if this is a typo, but you can throw a toLowerCase() to get 100% of what your question is after:

"John Smith".split("").reverse().join("").toLowerCase()

returns:

"htims nhoj"

As for the question in your title, you can specify the direction of a for loop in the last argument like so:

var reversed = [];
var name = "John Smith".split("");
for(var i = name.length-1; i >= 0; i--) {
    reversed.push(name[i]);
}
console.log(reversed.join(""));

Which will output:

"htimS nhoJ"

Upvotes: 11

Related Questions