How can I reverse an array in JavaScript without using libraries?

前端 未结 30 1005

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 anybo

相关标签:
30条回答
  • 2020-11-27 06:20

    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;
    }, []);
    
    0 讨论(0)
  • 2020-11-27 06:20

    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
    
    0 讨论(0)
  • 2020-11-27 06:22
    reveresed = [...array].reverse()
    
    0 讨论(0)
  • 2020-11-27 06:22

    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;
      }
    }
    
    0 讨论(0)
  • 2020-11-27 06:23

    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]] 
    }
    
    0 讨论(0)
  • 2020-11-27 06:23

    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;
    }
    
    0 讨论(0)
提交回复
热议问题