Zichen Ma
Zichen Ma

Reputation: 117

javascript reverse an array without using reverse()

I want to reverse an array without using reverse() function like this:

function reverse(array){
    var output = [];
    for (var i = 0; i<= array.length; i++){
        output.push(array.pop());
    }

    return output;
}

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

However, the it shows [7, 6, 5, 4] Can someone tell me, why my reverse function is wrong? Thanks in advance!

Upvotes: 10

Views: 48703

Answers (30)

zemil
zemil

Reputation: 5066

Python-like šŸ style of In-place algorithm:

function reverse(list) {
    let [left, right] = [0, list.length - 1];

    while (left < right) {
        [list[left], list[right]] = [list[right], list[left]];
        
        left += 1;
        right -= 1;
    }
    return list;
}

Upvotes: 0

Amila Welikala
Amila Welikala

Reputation: 11

You can try like this as well:

function reverse(arr) {
  for (let i = arr.length - 1; i >= arr.length / 2; i--) {
    arr[i] = arr[i] + arr[((arr.length - 1) - i)];
    arr[((arr.length - 1) - i)] = arr[i] - arr[((arr.length - 1) - i)];
    arr[i] = arr[i] - arr[((arr.length - 1) - i)];
  }
 return arr;
}
console.log(reverse([3, 5, 7, 2, 9, 6, 11])); // [11,6,9,2,7,5,3]

Upvotes: 1

ajitspyd
ajitspyd

Reputation: 1274

Simplest way to do it using array.map() and without using other array

const arr = [1,2,3,4,5]
arr.map((item, index) => {
    return arr[arr.length-index-1]
})

Upvotes: 0

Abhishek Sharma
Abhishek Sharma

Reputation: 1

    let checkValue = ["h","a","p","p","y"]
    let reverseValue = [];

    checkValue.map((data, i) => {
        x = checkValue.length - (i + 1);
        reverseValue[x] = data;
    })

Upvotes: 0

LOKESH NAIDU
LOKESH NAIDU

Reputation: 11

              const reverse = (array)=>{
              var output = [];
              for(let i=array.length; i>0; i--){
                output.push(array.pop());
              }
                console.log(output);
              }

              reverse([1, 2, 3, 4, 5, 6, 7, 8]);

Upvotes: 1

S.Alvi
S.Alvi

Reputation: 154

let array = [1,2,3,4,5,6];

const reverse = (array) => {

let reversed = [];

for(let i = array.length - 1; i >= 0; i--){
    reversed[array.length - i] = array[i];
}

return reversed;

}

console.log(reverse(array))

Upvotes: 0

Shatish Desai
Shatish Desai

Reputation: 605

Without Using any Pre-define function

const reverseArray = (array) => {
  for (let i = 0; i < Math.floor(array.length / 2); i++) {
    [array[i], array[array.length - i - 1]] = [
      array[array.length - i - 1],
      array[i]
    ];
  }
  return array;
};

Upvotes: 0

Irkenn
Irkenn

Reputation: 1

I found a way of reversing the array this way:

function reverse(arr){
  for (let i = arr.length-1; i >= 0; i--){ 
    arr.splice(i, 0, arr.shift());
    }
  return arr;
}

Upvotes: 0

Diego Elias
Diego Elias

Reputation: 121

This is an old question, but someone may find this helpful.

There are two main ways to do it:

First, out of place, you basically push the last element to a new array, and use the new array:

function arrReverse(arr) {
    let newArr = [];
            for(let i = 0; i<arr.length; i++){    
            newArr.push(arr.length -1 -i);       
    }
    return newArr;
}

arrReverse([0,1,2,3,4,5,6,7,8,9]);

Then there's in place. This is a bit tricky, but the way I think of it is like having four objects in front of you. You need to hold the first in your hand, then move the last item to the first place, and then place the item in your hand in the last place. Afterwards, you increase the leftmost side by one and decrease the rightmost side by one:

function reverseArr(arr) {
    let lh;
        
    for(let i = 0; i<arr.length/2; i++){
    
            lh = arr[i];
        arr[i] = arr[arr.length -i -1];
        arr[arr.length -i -1] = lh;
        
    }
    return arr;
}

reverseArr([0,1,2,3,4,5,6,7,8,9]);

Like so. I even named my variable lh for "left hand" to help the idea along.

Understanding arrays is massively important, and figuring out how they work will not only save you from unnecessarily long and tedious ways of solving this, but will also help you grasp certain data concepts way better!

Upvotes: 0

Shreyash Shetty
Shreyash Shetty

Reputation: 123

Array=[2,3,4,5]

 for(var i=0;i<Array.length/2;i++){
    var temp =Array[i];
    Array[i]=Array[Array.length-i-1]
    Array[Array.length-i-1]=temp
}

console.log(Array) //[5,4,3,2]

Upvotes: -1

Vitaliy
Vitaliy

Reputation: 1

One of shortest:

let reverse = arr = arr.map(arr.pop, [...arr])

Upvotes: 0

Bugs Bunny
Bugs Bunny

Reputation: 47

reverse=a=>a.map((x,y)=>a[a.length-1-y])

reverse=a=>a.map((x,y)=>a[a.length-1-y])

console.log(reverse(["Works","It","One","Line"]))

Upvotes: 0

ABHIDEEP SINHA
ABHIDEEP SINHA

Reputation: 1

function reverse(str1) {
  let newstr = [];
  let count = 0;
  for (let i = str1.length - 1; i >= 0; i--) {
    newstr[count] = str1[i];
    count++;
  }
  return newstr;
}
reverse(['x','y','z']);

Upvotes: -1

SUPPORT
SUPPORT

Reputation: 1

function reverse(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    arr.splice(i, 0, arr.pop())
  }
  return arr;
}
console.log(reverse([1, 2, 3, 4, 5]))
//without another array

Upvotes: 0

akhtarvahid
akhtarvahid

Reputation: 9769

Solution to reverse an array without using built-in function and extra space.

let arr = [1, 2, 3, 4, 5, 6, 7];
let n = arr.length-1;

for(let i=0; i<=n/2; i++) {
  let temp = arr[i];
  arr[i] = arr[n-i];
  arr[n-i] = temp;
}
console.log(arr);

Upvotes: 5

Maxim Belkin
Maxim Belkin

Reputation: 111

In ES6 this could be written as

reverse = (array) => array.map(array.pop, [... array]);

Upvotes: 10

oikumo
oikumo

Reputation: 11

And this one:

function reverseArray(arr) { 
    let top = arr.length - 1;
    let bottom = 0;
    let swap = 0;
    
    while (top - bottom >= 1) {
        swap = arr[bottom];
        arr[bottom] = arr[top];
        arr[top] = swap;
        bottom++;
        top--;
    }
}

Upvotes: 0

with reverse for loop


let array = ["ahmet", "mehmet", "aslı"]


    length = array.length
    newArray = [];
    for (let i = length-1; i >-1; i--) {

        newArray.push(array[i])

    }

    console.log(newArray)

Upvotes: 0

akula
akula

Reputation: 11

function rvrc(arr) {
  for (let i = 0; i < arr.length / 2; i++) {
    const buffer = arr[i];

    arr[i] = arr[arr.length - 1 - i];
    arr[arr.length - 1 - i] = buffer;
  }
};

Upvotes: 1

SpicySpices
SpicySpices

Reputation: 1

You can use .map as it is perfect for this situation and is only 1 line:

const reverse = a =>{ i=a.length; return a.map(_=>a[i-=1]) }

This will take the array, and for each index, change it to the length of the array - index, or the opposite side of the array.

Upvotes: 0

shimmiChristo
shimmiChristo

Reputation: 33

This piece allows to reverse the array in place, without pop, splice, or push.

var arr = [1, 2, 3, 4, 5];
function reverseArrayInPlace(arr2) {
  var half = Math.floor(arr2.length / 2);
  for (var i = 0; i < half; i++) {
    var temp = arr2[arr2.length - 1 - i];
    arr2[arr2.length - 1 - i] = arr2[i];
    arr2[i] = temp;
  }
  return arr2;
}

Upvotes: 2

pitrioptixiop
pitrioptixiop

Reputation: 1

Here, let's define the function

function rev(arr) {
  const na = [];
  for (let i=0; i<arr.length; i++) {
    na.push(arr[arr.length-i])
  }
  return na;
}

Let's say your array is defined as 'abca' and contains ['a','b','c','d','e','foo','bar']

We would do:

var reva = rev(abca)

This would make 'reva' return ['bar','foo','e','d','c','b','a']. I hope I helped!

Upvotes: 0

viz_tm
viz_tm

Reputation: 115

This piece of code will work without using a second array. It is using the built in method splice.

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

Upvotes: 0

blaze_125
blaze_125

Reputation: 2317

No need to pop anything... Just iterate through the existing array in reverse order to make your new one.

function reverse(array){
    var output = [];
    for (var i = array.length - 1; i> -1; i--){
        output.push(array[i]);
    }

    return output;
}

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

Edit after answer got accepted.

A link in a comment on your opening post made me test my way VS the accepted answer's way. I was pleased to see that my way, at least in my case, turned out to be faster every single time. By a small margin but, faster non the less.

Here's the copy/paste of what I used to test it (tested from Firefox developer scratch pad):

function reverseMyWay(array){
    var output = [];
    for (var i = array.length - 1; i> -1; i--){
        output.push(array[i]);
    }

    return output;
}

function reverseTheirWay(array) {
  var output = [];
  while (array.length) {
    output.push(array.pop());
  }

  return output;
}

function JustDoIt(){
    console.log("their way starts")
    var startOf = new Date().getTime();
    for(var p = 0; p < 10000; p++)
        {
            console.log(reverseTheirWay([7,6,5,4,3,2,1]))
        }
    var endOf = new Date().getTime();
    console.log("ran for " + (endOf - startOf) + " ms");
    console.log("their way ends")

}


function JustDoIMyWay(){
    console.log("my way starts")
    var startOf = new Date().getTime();
    for(var p = 0; p < 10000; p++)
        {
            console.log(reverseMyWay([7,6,5,4,3,2,1]))
        }
    var endOf = new Date().getTime();
    console.log("ran for " + (endOf - startOf) + " ms");
    console.log("my way ends")
}

JustDoIt();
JustDoIMyWay();

Upvotes: 5

Geeky
Geeky

Reputation: 7498

You can make use of Array.prototype.reduceright and reverse it

check the following snippet

var arr = ([1, 2, 3, 4, 5, 6, 7]).reduceRight(function(previous, current) {
  previous.push(current);
  return previous;
}, []);

console.log(arr);

Upvotes: 7

zzzzBov
zzzzBov

Reputation: 179046

You are modifying the existing array with your reverse function, which is affecting array.length.

Don't pop off the array, just access the item in the array and unshift the item on the new array so that the first element of the existing array becomes the last element of the new array:

function reverse(array){
  var output = [],
      i;
  for (i = 0; i < array.length; i++){
    output.unshift(array[i]);
  }

  return output;
}

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

If you'd like to modify the array in-place similar to how Array.prototype.reverse does (it's generally inadvisable to cause side-effects), you can splice the array, and unshift the item back on at the beginning:

function reverse(array) {
  var i,
      tmp;
  for (i = 1; i < array.length; i++) {
    tmp = array.splice(i, 1)[0];
    array.unshift(tmp);
  }
  return array;
}

var a = [1, 2, 3, 4, 5];
console.log('reverse result', reverse(a));
console.log('a', a);

Upvotes: 2

nottu
nottu

Reputation: 379

You're modifying the original array and changing it's size. instead of a for loop you could use a while

    function reverse(array){
        var output = [];
        while(array.length){
            //this removes the last element making the length smaller
            output.push(array.pop());
        }

        return output;
}

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

Upvotes: 1

Liran H
Liran H

Reputation: 10579

This happens because every time you do array.pop(), whilst it does return the last index in the array, it also removes it from the array. The loop recalculates the length of the array at each iteration. Because the array gets 1 index shorter at each iteration, you get a much shorter array returned from the function.

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65806

As you pop items off the first array, it's length changes and your loop count is shortened. You need to cache the original length of the original array so that the loop will run the correct amount of times.

function reverse(array){
    var output = [];
    var len = array.length;
    for (var i = 0; i< len; i++){
        output.push(array.pop());
    }

    return output;
}

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

Upvotes: 1

TimoStaudinger
TimoStaudinger

Reputation: 42460

array.pop() removes the popped element from the array, reducing its size by one. Once you're at i === 4, your break condition no longer evaluates to true and the loop ends.


One possible solution:

function reverse(array) {
  var output = [];
  while (array.length) {
    output.push(array.pop());
  }

  return output;
}

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

Upvotes: 14

Related Questions