Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 946
Derek 朕會功夫 Avatar asked Apr 16 '12 02:04

Derek 朕會功夫


People also ask

How do you reverse an array without using another array?

Steps to reverse an array without using another array in C:Set i=0 to point to the first element and j=length-1 to point to the last element of the array. Run while loop with the condition i<j . Inside loop swap ith and jth element in the array. Increment i and decrement j .


Video Answer


2 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.

like image 96
Andreas Wong Avatar answered Sep 24 '22 01:09

Andreas Wong


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]
like image 31
Rohit Shelhalkar Avatar answered Sep 21 '22 01:09

Rohit Shelhalkar