/javascript

6 Ways to reverse an Array in Javascript

In modern web applications as well as any application, which runs on the web, javascript plays a major role. Any response which you get from the API will be an array and you will have to manipulate it and perform operations on top of it.

In my previous blog I have discussed about some array tips and tricks which will help you to write better javascript code. Today i will share you some of the top ways in which you can reverse an array.

We can reverse arrays either by modifying the source array or without modifying the source.

Let’s start by declaring a const array. Here the output stays same for all of the below methods.

const numbers = [1, 2, 3, 4, 5];

//output
[5, 4, 3, 2, 1];

Using Reverse

numbers.reverse();

Using For Loop

var reversedNumbers = [];
for (let i = numbers.length - 1; i >= 0; i--) {
  reversedNumbers.push(numbers[i]);
}
console.log(reversedNumbers);

Using slice() and reverse()

var reversedNumbers = numbers.slice().reverse();

Using spread operator with reverse()

var reversedNumbers = [...numbers].reverse();

Using spread operator with reduce()

var reversedNumbers = numbers.reduce((acc, val) => {
  return [val, ...acc];
}, []);

Using map() with unshift()

let reversedNumbers = [];
numbers.map(n => {
  reversedNumbers.unshift(n);
});

I think the easiest one to choose is reverse() emoji-satisfied. I’m a lazy guy. You can choose which ever you feel will work for your use case. Thanks for reading emoji-pray

Stay tuned to https://haricodes.com for more amazing blogs.

HariHaran

HariHaran

Full Stack Developer

Read More