user6120694
user6120694

Reputation:

Reversing an array manually

I am learning JS and stuck on this thing. I need to reverse an array with function that takes an argument as value. Like this:

value = [1, 2, 3, 4, 5];
reverse(value);
console.log(value);
//[5, 4, 3, 2, 1]

I wrote this function and can't understand why it won't work:

function reverseArrayInPlace(x){
  var p = 0, y = x;
  for(i = y.length-1; i>=0; i--){
    x[p] = y[i];
    p++;
    }
  return x;
  }

It s returning this: [5, 4, 3, 4, 5] Maybe I've done something stupid in here, but still can you point me where is the mistake? Thank you!

Upvotes: 1

Views: 534

Answers (5)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You could loop until the middle of the modified array. And simply swap elements

function reverseArrayInPlace(x) {
  for (var i = 0, last = x.length - 1, mid = last/2, tmp; i <= mid; i++) {
    tmp = x[i];
    x[i] = x[last - i];
    x[last - i] = tmp;
    
  }
  return x;
}

const arr = [1,2,3,4,5]

reverseArrayInPlace(arr)

console.log(JSON.stringify(arr))
const arr2 = [1, 2, 3, 4, 5, 6]

reverseArrayInPlace(arr2)

console.log(JSON.stringify(arr2))

Upvotes: 4

Sandeep Nayak
Sandeep Nayak

Reputation: 4757

You are modifying the original array as well, when you write y=x as they are copied by reference.

Instead do this:

function reverseArrayInPlace(x) {
  var p = 0, y = [];
  for (i = x.length - 1; i >= 0; i--) {
    y[p] = x[i];
    p++;
  }
  return y;
}

console.log(reverseArrayInPlace([1, 2, 3, 4, 5]))

Upvotes: 2

brijrajsinh
brijrajsinh

Reputation: 453

Try this this will replace original array as per your requirement:

value = [1, 2, 3, 4, 5];
value = value.reverse();
console.log(value);

or you can do like this:

value = [1, 2, 3, 4, 5];
reverse(value);
console.log(value);

function reverse(x) {
  var p = 0, y = [];
  for (i = x.length - 1; i >= 0; i--) {
    y[p] = x[i];
    p++;
  }
  value = y;
}

Upvotes: 0

harsh zalavadiya
harsh zalavadiya

Reputation: 385

Actually you are overriding the original array so you need to clone the array to temporary variable and then ressign the values

value = [1, 2, 3, 4, 5];

but you can do this directly with this function

console.log(value.reverse());

Upvotes: 0

Nick Coad
Nick Coad

Reputation: 3694

This line:

var p = 0, y = x;

Is storing a reference to the array stored in x, into the variable y. In other words, x and y are pointing to the same array.

To fix this, build a new array:

function reverseArrayInPlace(x) {
    var p = 0, y = [];

    for (i = x.length-1; i>=0; i--) {
        y[p] = x[i];
        p++;
    }
    return y;
}

If you absolutely need to modify the original array, just copy the reversed array back into the original:

function reverseArrayInPlace(x) {
    var p = 0, y = [];

    for (i = x.length-1; i>=0; i--) {
        y[p] = x[i];
        p++;
    }

    for (var i = 0; i < y.length; i++) {
        x[i] = y[i];
    }

    return x;
}

Upvotes: 2

Related Questions