paint-brush
How to Flip an Array in JavaScriptby@moibra
263 reads

How to Flip an Array in JavaScript

by Mohamed IbrahimJanuary 30th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this article we will learn how to reverse an array in JavaScript. There are two ways, the first is easy because there's a built-in function in JavaScript that does this, and the second is to create that function with ourselves. It is better for you in the production stage to use what is in the language, but it is better to understand what is happening behind the scenes.
featured image - How to Flip an Array in JavaScript
Mohamed Ibrahim HackerNoon profile picture

In this article we will learn how to reverse an array in JavaScript.


There's more than one way to do this:

  • Using reverse() method (Built In)
  • Using for loop


There are two ways, the first is easy because there's a built-in function in JavaScript that does this, and the second is to create that function with ourselves.


It is better for you in the production stage to use what is in the language, but in the learning stage it is better to understand what is happening behind the scenes.


Our Problem

Now what is our problem? The problem is that there's an array and we want to reverse it.


Imagine that there is a array like that:

[1, 2, 3, 4, 5]


And we want to reverse it to be like this

[5, 4, 3, 2, 1]


As we said earlier, we can solve the problem in two ways.


  • Using reverse() method (Built In)
  • Using for loop

Using reverse() method (Built In)

We can use reverse() method to solve our problem.



**Example

// Array
let myArray = [1, 2, 3, 4, 5];

// Reverse the array
let reversedArr = myArray.reverse();

// Result:
console.log(reversedArr);



**Output

[ 5, 4, 3, 2, 1 ]

Using for loop

Now, before writing the code, we must understand how we will solve this problem by for loop?


First, iteration using for iterate over every element in the array, right?


Well here it means that we can start from the last element in the array to the first element (the opposite)


Then we can add each element to a new array.


Summarize the solution as follows:


  • Iterate over every element in our array

  • Iteration will start from the last to the first


5, 4, 3, 2, 1


  • Add each element to a new array.



**Full code

// Array
let myArray = [1, 2, 3, 4, 5];

// Create new array
let result = [];

// Iterate over every element in our array
for (let i = myArray.length - 1; i >= 0; i--) {
    // Add every element to new array
    result.push(myArray[i]);
}

// Result:
console.log(result);



**Output

[ 5, 4, 3, 2, 1 ]


Hope this helps. Cheers!


Also published here.