Reputation: 95
I'm a JavaScript beginner and I've written the snippet below which in my mind should return an array: [5, 4, 3, 2, 1], but instead it returns [5]. I realize there are better ways to achieve the result, but what I'm trying to understand is why my solution doesn't work.
function reverseArray(array) {
for (var i = 3; i >= 0; i--)
array.concat(array.slice(i,i+1));
for (var i = 3; i >= 0; i--)
array.shift();
return array;
};
var arrayValue = [1, 2, 3, 4, 5];
reverseArray(arrayValue);
console.log(arrayValue);
// JS Bin returns: [5]
The shift method appears to work, but the concat/slice code doesn't seem to alter the array. Why not? When I test the line as stand alone code it works fine. Any explanation would be greatly appreciated. Thanks!
Upvotes: 0
Views: 58
Reputation: 23
There's answer how work concat
and shift
functions. Here's small snippet how to make this function easily by algorithmic approach if you don't want to create local copy of existing array.
function reverseArray(array) {
var i = 0;
var j = array.length - 1;
while (i < j) {
var tempArrayElement = array[i];
array[i] = array[j];
array[j] = tempArrayElement;
i++;
j--;
}
}
Upvotes: 0
Reputation: 664277
What Mike said: array.concat(…)
does not modify array
, it creates a new array which is then ignored.
It seems you only want to append a single value - that's what push
does:
function reverseArray(array) {
for (var i = 3; i >= 0; i--)
array.push(array[i]);
for (var i = 3; i >= 0; i--)
array.shift();
return array;
}
You probably also want to use a variable value derived from array.length
instead of the constant 3
.
Upvotes: 2
Reputation: 32511
concat
and slice
creates a new array without changing the original. shift
modifies the array it acts on.
Basically, you're generating a bunch of new sub arrays with concat
but you aren't doing anything with them.
Upvotes: 2