How Can I Reverse an Array in Javascript Without Using Libraries?

I am saving some data in order using arrays, and I want to add a function that the user can reverse the list. I can't think of any possible method, so if anybody knows how, please help.

2

36 Answers

Javascript has a reverse() method that you can call in an array

var a = [3,5,7,8];
a.reverse(); // 8 7 5 3

Not sure if that's what you mean by 'libraries you can't use', I'm guessing something to do with practice. If that's the case, you can implement your own version of .reverse()

function reverseArr(input) {
    var ret = new Array;
    for(var i = input.length-1; i >= 0; i--) {
        ret.push(input[i]);
    }
    return ret;
}

var a = [3,5,7,8]
var b = reverseArr(a);

Do note that the built-in .reverse() method operates on the original array, thus you don't need to reassign a.

1

Array.prototype.reverse() is all you need to do this work. See compatibility table.

var myArray = [20, 40, 80, 100];
var revMyArr = [].concat(myArray).reverse();
console.log(revMyArr);
// [100, 80, 40, 20]
2

Heres a functional way to do it.

const array = [1,2,3,4,5,6,"taco"];

function reverse(array){
  return array.map((item,idx) => array[array.length-1-idx])
}
2

20 bytes

let reverse=a=>[...a].map(a.pop,a)
8

The shortest reverse method I've seen is this one:

let reverse = a=>a.sort(a=>1)
4
reveresed = [...array].reverse()
const original = [1, 2, 3, 4];
const reversed = [...original].reverse(); // 4 3 2 1

Concise and leaves the original unchanged.

2

**

Shortest reverse array method without using reverse method:

**

 var a = [0, 1, 4, 1, 3, 9, 3, 7, 8544, 4, 2, 1, 2, 3];

 a.map(a.pop,[...a]); 
// returns [3, 2, 1, 2, 4, 8544, 7, 3, 9, 3, 1, 4, 1, 0]

a.pop method takes an last element off and puts upfront with spread operator ()

MDN links for reference:

1

This is what you want:

array.reverse();
James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.