So we are practicing functional javascript in my programming class with this assignment and I just can't get it to work right. Any advice in making this code work would be appreciated. Everything but the body was given for me to use. Here is what I have come up with: (It is always sending me just the first array index content rather than all of them reversed. I tried changing it to
if(arr.length <= 1) return arr;
but that never hits the base case.)
function ReverseArray(arr) {
//base case
if(arr.length == 1)
{
return arr[0];
}
if(arr.length == 0)
{
return 0;
}
var head = arr.pop;
var newArr = [head, ReverseArray(arr)];
return newArr;
}
3 Answers 3
x = y <--assignment
z == y <-- comparison
Looking at your code:
if(arr.length = 1)
needs to be
if(arr.length == 1)
same with the zero check
AND you are not calling pop
var head = arr.pop;
you need to parenthesis
var head = arr.pop();
Comments
This is the most precise and clean way to do it in a single line with the ternary operator.
function reverse(arr) {
return arr.length < 2 ? arr : [arr.pop()].concat(reverse(arr));
}
console.log(reverse([4, 3, 3, 1]));
Comments
Here's a runnable example with a working function. FYI there is also a built-in function that will do this for you.
I think other than the confusion with assignment/comparison operators, when you were building the result array, you should be using Array.concat() to concatenate your array, instead you were building a new array where the second item was an array itself.
var a = [1,2,3,4,5];
console.log(ReverseArray(a));
function ReverseArray(arr) {
if(arr.length < 2) {
return arr;
} else {
return [arr.pop()].concat(ReverseArray(arr));
}
}
Comments
Explore related questions
See similar questions with these tags.
[end0, [....]]. After two iterations, you'll have this[end0, [end1, [...]]]and it will keep nesting arrays further and further. Your approach will not work. You need a new design. Perhaps you want to use.concat()to add two arrays together rather than embedding one in another. If you want help with a new design, you will have to better describe the rules of the assignment sincearr.reverse()already exists to do this.if (arr.length < 2) return arr;