Reversing an array without 'reverse' or duplicating an array

5.6k Views Asked by At

I'm trying to solve the following exercise:

Reverse an array without using the reverse method, without using a second array, and without duplicating any of the values.

I've thought about making the array an object and then updating the array from the end to the beginning but I figured you can just update it as well.

Tried something simple like:

function reverseArray(array) {
  for (var i = 0; i < array.length; i++) {
    // var elem = array.shift();
    var elem = array.shift()
    array.push(elem)
  }
  return array
}

array = ['a', 'b','c','d','e'];

reverseArray(array);

But that doesn't really change it. Any advice or explanation on how to do this?

10

There are 10 best solutions below

0
On BEST ANSWER

With ES6 syntax you don't need to copy a value into a temporary variable (is that what the last requirement is about?).

function reverse(arr) {
    for(let i = 0, j = arr.length-1; i < j; i++, j--)
        [arr[i], arr[j]] = [arr[j], arr[i]];
}

const arr = ['a','b','c','d','e'];
reverse(arr);
console.log(arr);

One may argue that arrays are created here (if engines don't optimise this away), just like splice also creates an array (as its return value).

0
On

You could use a spread syntax ..., rest parameters ... and return the swapped items with a recursive and functional approach.

const
    _ = (...a) => a,
    rev = (a, ...rest) => rest.length ? _(...rev(...rest), a) : _(a),
    reverseArray = array => rev(...array);

console.log(reverseArray(['a', 'b', 'c', 'd', 'e']));
console.log(reverseArray(['a']));
console.log(reverseArray(['a', 'b']));
.as-console-wrapper { max-height: 100% !important; top: 0; }

1
On

The following will work reverse an array without using the reverse method. It works by swapping the first and last elements, then the second and second-to-last elements, then the third and third-to-last elements, etc until the i is no longer less than (<) than j.

function reverse(arr) {
  for(var i = 0, j = arr.length-1; i < j; i++, j--) {
    var tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
  }
  return arr;
};

var reversed = reverse(['a','b','c','d','e']);
console.log(reversed);

1
On

https://jsfiddle.net/pa2fqa8n/1/

a = ['a', 'b', 'c', 'd', 'e'];
for(var i = 0; i < a.length-1; i++){
  for(var j = 0; j < a.length-i-1; j++){
    var k = a[j];
    a[j] = a[j+1];
    a[j+1] = k;
  }
}

First iteration of inner loop moves the first element to the end, and the rest of the elements forward once. Each following iteration does the same thing, but 1 less than the previous iteration.

4
On

Here's how, without copies, temporary arrays or variables to hold values, or using Array.reverse().Modifying the array in place

function reverseArray(array) {
  var len = array.length;
  for (var i=len,j=-1; j++,i--;)  array.unshift( array[len-1-i+(j)] );
  array.length = len;
}

var array = ['a', 'b','c','d','e'];

reverseArray(array);
console.log(array);

It inserts the values backwards into the beginning of the array, pushing the old values to the end, and then slicing them of by resetting the arrays length after the iteration has completed.

0
On

I had to use a swap variable, does that violate "without duplicating any of the values"?

var test1 = [2, '5', 6, 'a', 'Z'];
var test2 = [2, '5', false, 'a', 'Z', {a: 'whatevs'}];

console.log('test1 before', JSON.stringify(test1));
console.log('test2 before', JSON.stringify(test2));

reversarooni(test1);
reversarooni(test2);

console.log('test1 after', JSON.stringify(test1));
console.log('test2 after', JSON.stringify(test2));

function reversarooni(inputArray) {
  var index = 0;
  var len = inputArray.length;
  
  for(; index < len / 2; index++) {
    var swap = inputArray[index];
    inputArray[index] = inputArray[(len - 1) - index];
    inputArray[(len - 1) - index] = swap;
  }
}

1
On

array = ['a', 'b', 'c', 'd', 'e'];
console.log(array);

for (var i = 0; i < Math.floor(array.length / 2); i++) {
  var item = array[i];
  array[i] = array[array.length - i - 1];
  array[array.length - i - 1] = item;
}
console.log(array);

0
On

Here is a minimal approach. Given var arr = [1,2,3,4], this loop will mutate arr to [4,3,2,1]:

for (var i = 0; i < arr.length - 1; i++) {
    arr.splice(i, 0, arr.pop());
}
0
On

function printReverse(array) {
  for (i = array.length-1; i > -1; i--) {
    console.log(array[i]); //4,3,2,1
  }
}

printReverse([1, 2, 3, 4]);

This worked for me.

0
On

function reverseArray(a) {

    const halfLength = a.length / 2;
for (let i = 0; i< halfLength; i++){
const start = a[i]
a[i] = a[a.length-i-1]
a[a.length-i-1] = start
}
   

return a;
}