DEV Community

Cover image for Reverse An Array - 3 Methods

Reverse An Array - 3 Methods

Amritanshu Dev Rawat on June 08, 2021

Method 1 - Revere with For Loop and print public class ReverseArray { public static void main(String[] args) { // Array with some element int[...
Collapse
 
lexlohr profile image
Alex Lohr

This seems to be C++, not JavaScript. In JavaScript, you'd have

const myArray = [10,22,33,11,88,9,2]

// native (will change the original reference)
myArray.reverse()
console.log(myArray)

myArray.reverse() // change it back

// functional
const functionalReversedMyArray = myArray.reduce((result, item) => [item, ...result], [])
console.log(functionalReversedMyArray)

// imperative
const imperativeReversedMyArray = []
for (const index in myArray) {
  imperativeReversedMyArray.unshift(myArray[index])
}
console.log(imperativeReversedMyArray)

// recursive
const recursiveArrayReversal = (inputArray, partiallyReversed = []) => 
  inputArray.length
  ? recursiveArrayReversal(inputArray.slice(1), [inputArray[0], ...partiallyReversed])
  : partiallyReversed
const recursiveReversedMyArray = recursiveArrayReversal(myArray)
console.log(recursiveReversedMyArray)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
amritanshu profile image
Amritanshu Dev Rawat

Thanks :) That was JAVA :)

Collapse
 
longwater1234 profile image
Davis Tibbz • Edited

Here is a crazy one 😀:

public static int[] reverse(int[] array) {
       return IntStream.range(0, array.length).map(i -> array[array.length - 1 - i]).toArray();
    }
 public static void main(String[] args) {
    //integer array 'a'
     var a = reverse(new int[]{2, 4, 5, 6, 7, 8});
    System.out.println(Arrays.toString(a));
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
junejuly profile image
June July

Great work bro!

Collapse
 
amritanshu profile image
Amritanshu Dev Rawat

:) thanks