0

If i have a list and i want to change the list order using the recursion. How can i do that? Is there any simple way or best way to do that?

Here is something that i have think about, how it works:

list = [0,1,2,3,4,5,6,7,8,9];

if if(list.length<1){
    return list;
}else{
    //making list last to first. 
}

should return this: 
[9,8,7,6,5,4,3,2,1,0]

I'm quite new with this recursion, if someone could explain a little bit, how it works. Thanks

user7697691
  • 303
  • 2
  • 9
  • Why do you want to use recursion? `list.reverse()` seems simpler. – pablochan Oct 29 '17 at 22:23
  • If you need to reverse an array, you could use the [built-in function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse). If it's an assignment that specifically requires you to use recursion, maybe you should try it yourself. – GolezTrol Oct 29 '17 at 22:24
  • Possible duplicate of [How can I reverse an array in JavaScript without using libraries?](https://stackoverflow.com/questions/10168034/how-can-i-reverse-an-array-in-javascript-without-using-libraries) – GolezTrol Oct 29 '17 at 22:25
  • Is this a homework question? Have you tried to create a recursive function? You can use a recursive function to create a stack of items and then read them back off the stack in reverse order (i.e. create a push down automaton). – david25272 Oct 29 '17 at 23:08
  • Don't forget to vote and accept if you find it helpful! – developer_hatch Oct 30 '17 at 00:51

2 Answers2

0

If you really don't want to use Array#reverse, you can over complicate it with a recursion using Array#slice and Array#concat:

var list = [0,1,2,3,4,5,6,7,8,9];

function reverse(list) {
  return list.slice(-1).concat((list.length ? reverse(list.slice(0, -1)) : []));
}

console.log(reverse(list));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Thank you so much for answering. Would be nice, if you could explain a little bit, what "?" means in that code. – user7697691 Oct 29 '17 at 22:56
  • It's a [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator). – Ori Drori Oct 29 '17 at 23:10
0

If the idea is practice recursion, you can see this code, I will explain in comments:

list = [0,1,2,3,4,5,6,7,8,9];

function rev(list, reversed=[]){
  if(list.length === 0){ // if the list is empty, you return the reversed Array
    console.log(reversed)
    return reversed;
  }else{
    reversed.push(list.pop()) // if not empty, you add the last element as the first element of the reversed list 
    return rev(list, reversed) // then you continue the recursion with the list modified
  }
}



console.log(rev(list))
developer_hatch
  • 15,898
  • 3
  • 42
  • 75