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

前端 未结 30 1001

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:08

    20 bytes

    let reverse=a=>[...a].map(a.pop,a)
    
    0 讨论(0)
  • 2020-11-27 06:08
    array.reverse() 
    

    Above will reverse your array but modifying the original. If you don't want to modify the original array then you can do this:

    var arrayOne = [1,2,3,4,5];
    
    var reverse = function(array){
        var arrayOne = array
        var array2 = [];
    
        for (var i = arrayOne.length-1; i >= 0; i--){
          array2.push(arrayOne[i])
        } 
        return array2
    }
    
    reverse(arrayOne)
    
    0 讨论(0)
  • 2020-11-27 06:08

    How about this?:

      function reverse(arr) {
        function doReverse(a, left, right) {
          if (left >= right) {
            return a;
          }
          const temp = a[left];
          a[left] = a[right];
          a[right] = temp;
          left++;
          right--;
          return doReverse(a, left, right);
        }
    
        return doReverse(arr, 0, arr.length - 1);
      }
    
      console.log(reverse([1,2,3,4]));
    

    https://jsfiddle.net/ygpnt593/8/

    0 讨论(0)
  • 2020-11-27 06:11

    Using ES6 rest operator and arrow function.

    const reverse = ([x, ...s]) => x ? [...reverse(s), x] : [];
    reverse([1,2,3,4,5]) //[5, 4, 3, 2, 1]
    
    0 讨论(0)
  • 2020-11-27 06:12

    Below is a solution with best space and time complexity

    function reverse(arr){
    let i = 0;
    let j = arr.length-1; 
    while(i<j){
    arr[j] = arr[j]+arr[i];
    arr[i] = arr[j] - arr[i];
    arr[j] = arr[j] - arr[i];
    i++;
    j--;
    }
    return arr;
    }
    var arr = [1,2,3,4,5,6,7,8,9]
    reverse(arr);
    

    output => [9,8,7,6,5,4,3,2,1]

    0 讨论(0)
  • 2020-11-27 06:13

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

    let reverse = a=>a.sort(a=>1)
    
    0 讨论(0)
提交回复
热议问题