I am saving some data in order using array
s, and I want to add a function that the user can reverse the list. I can\'t think of any possible method, so if anybo
It can also be achieved using map method.
[1, 2, 3].map((value, index, arr) => arr[arr.length - index - 1])); // [3, 2, 1]
Or using reduce (little longer approach)
[1, 2, 3].reduce((acc, curr, index, arr) => {
acc[arr.length - index - 1] = curr;
return acc;
}, []);
This function will work with arrays that have may have gaps between their indices.
function reverse( a ) {
var b = [], c = [] ;
a.forEach( function( v ) { b.push( v ) } ) ;
a.forEach( function( v, i ) { c[i] = b.pop() } ) ;
return c ;
}
var a= [] ; a[1] = 2 ; a[3] = 4 ; a[7] = 6 ; a[9] = 8 ;
a = reverse( a ) ;
var s = '' ;
a.forEach( function( v, i ) { s += 'a[' + i + '] = ' + v + ' ' } ) ;
console.log( s ) ;
// a[1] = 8 a[3] = 6 a[7] = 4 a[9] = 2
reveresed = [...array].reverse()
reverse array and sub-array (in place) with ES6.
function reverse(array, i=0, j=array.length-1){
while (i < j){
[array[i], array[j]] = [array[j], array[i]];
++i;
--j;
}
}
reverse in place with variable swapping (mutative)
const myArr = ["a", "b", "c", "d"];
for (let i = 0; i < (myArr.length - 1) / 2; i++) {
const lastIndex = myArr.length - 1 - i;
[myArr[i], myArr[lastIndex]] = [myArr[lastIndex], myArr[i]]
}
We have reverse() function to reverse the given array in JS.
var a = [7,8,9];
a.reverse(); // 9 8 7
function reverseArr(input)
{
var ret = new Array;
for(var i = input.length-1; i >= 0; i--)
{
ret.push(input[i]);
}
return ret;
}