0

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!

3
  • why not exchange the first and last element and first +1 and last -1, and so on? Commented Sep 16, 2016 at 21:58
  • 1
    arrayValue.reverse() Commented Sep 16, 2016 at 22:00
  • the concat/slice code doesn't seem to alter the array. Why not? because neither concat nor slice modify the array. It's a boring explanation, I know, but it's the explanation. Commented Sep 16, 2016 at 22:01

3 Answers 3

2

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.

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

3 Comments

just personal. i appreciate your answers.
@NinaScholz Thanks :) I appreciate yours as well. High quality stuff.
Thank you! This gets at the heart of what I'm trying to understand (simple as it may seem). And thanks to everyone else who gave his or her advice — all good stuff.
2

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.

Comments

0

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--;
  }
}

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.