-4

I want to get the reverse of this array, in this case ([4,3,2,1]). The problem is I can use no reverse or other shorcuts.

const ar = [1, 2, 3, 4]

const reverse = function (arr) {


    let x = arr;

        for(i=0; i<x.length;i++) {

        x[x.length-i-1]=x[i];


        }
return x;   
};

const reversedArray = reverse(ar);
console.log(reversedArray);

I thought it must be working, however when I run I get [ 1, 2, 2, 1 ] as an output. Which is because when i=1 at the second index there is no longer 3. What can I do?

8
  • 6
    ar.reverse() comes to mind ? Commented Oct 18, 2016 at 15:12
  • Array.prototype.reverse Commented Oct 18, 2016 at 15:12
  • 1
    Reverse in another array. Commented Oct 18, 2016 at 15:12
  • 1
    run the array up to x.length/2 over two and swap x[i] and x[x.length-i-1] Commented Oct 18, 2016 at 15:12
  • @adeneo the essence of the probelem is to use no helpers, or shortcuts Commented Oct 18, 2016 at 15:16

6 Answers 6

2

It's like swapping two variables without using a temp variable

const ar = [1, 2, 3, 4]

const reverse = function (arr) {


    let x = arr, len = x.length-1;

        for(i=0; i<x.length/2;i++) {

          x[i]+=x[len-i];
          x[len-i]=x[i]-x[len-i];
          x[i]-=x[len-i]


        }
return x;   
};

const reversedArray = reverse(ar);
console.log(reversedArray);

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

Comments

1

Here is a simple example. But you can achieve the same result with other methods.

function reverse(array){
    var new_array = [];
    for(var i = 0; i< array.length; i++){
        new_array[i] = array[array.length -i - 1];
    }
    return new_array;
}

//how to use
reverse([1,2,3,4,5]); //output

Comments

1

You can keep it simple by using a regular for loop, and then just unshifting the values onto a new array:

function reverse(arr) {
  let reversed = [];
  for (let i = 0; i < arr.length; i++) {
    reversed.unshift(arr[i]);
  }
  return reversed;
}


console.log(reverse([1, 2, 3, 4]));
console.log(reverse([6, 7, 8, 9]));

Comments

1

With a while loop and starting from the end of the array :

var arr = [1, 2, 3, 4];

function arrReverse(arr) {
  var res = [];
  var max = arr.length - 1;
  while (max > -1) {
    res.push(arr[max]);
    max -= 1;
  }
  return res;
}

var res = arrReverse(arr);
console.log(res);

Comments

0

You're changing the array while you do that because of Javascript's references.

You can use array.prototype.reverse (which is used as [].reverse()) Or you should set a new array and return it.

Comments

-1

Don't use the array as a constant. It is probably not letting you make changes in the array.

Then use the reverse method:

ar.reverse();

1 Comment

From the question: "The problem is I can use no reverse or other shorcuts."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.