I am trying to write a function on JS which accepts the given array and reverses it. I know that there is a special method for this, but there is a desire like a beginner to write manually. I give a code which for not clear to me reasons returns an empty array.

function reverseArray(myArray) { var newMyArray = []; for (var i = myArray.length; i > 0; i--) { newMyArray.unshift(myArray.pop()); } return newMyArray; } 

    3 answers 3

    Your function works, but incorrectly (see comment). Well, there is nothing in the source array after it.

     function reverseInPlace(anArray) { for (var i = 0; i < anArray.length / 2; i++) { var temp = anArray[i]; anArray[i] = anArray[myArray.length - 1 - i]; anArray[anArray.length - 1 - i] = temp; } } function reverseArray(myArray) { var newMyArray = []; for (var i = myArray.length; i > 0; i--) { newMyArray.unshift(myArray.pop()); // needs newMyArray.push instead } return newMyArray; } var myArray = [1, 2, 3, 4, 5]; var newArray = reverseArray(myArray); console.log(newArray); console.log(myArray); myArray = [1, 2, 3, 4, 5]; reverseInPlace(myArray); console.log(myArray); 

       const revert = a => a.reduceRight((_, e) => (_.push(e), _), []); console.info(revert([1, 2, 3, 4, 5])); 

      • will not work in IE11 - Alexey Shimansky
      • @ Alexey Shimansky, the donkey died, long live the EDGE . Well, or polyfill, for an ass, he is needed everywhere. - user207618
      • I do not agree. A lot of people use and develop under IE> = 9 ...... so all these ES6 things are still wicked devilry .... - Alexey Shimansky
      • @ Alexey Shimansky, one cannot delay the progress because of the frail branches of development (although there, apparently, they did not even think of reading the standard). In any case, there is Babel , he will take care of them without prejudice to the developer. - user207618

      With changing the array itself

       function reverse(a) { for (var l=0, r=a.length-1; l<r; ++l, --r) { var temp = a[l]; a[l] = a[r]; a[r] = temp; } return a; } console.log("" + reverse([])); console.log("" + reverse([1])); console.log("" + reverse([1,2])); console.log("" + reverse([1,2,3])); console.log("" + reverse([1,2,3,4,5,6,7,8])); console.log("" + reverse([1,2,3,4,5,6,7,8,9])); 

      With the creation of a new array

       function reverse(a) { var res = []; for (var q=a.length-1; ~q; --q) { res.push(a[q]); } return res; } console.log("" + reverse([])); console.log("" + reverse([1])); console.log("" + reverse([1,2])); console.log("" + reverse([1,2,3])); console.log("" + reverse([1,2,3,4,5,6,7,8])); console.log("" + reverse([1,2,3,4,5,6,7,8,9]));