JavaScript provides amazing functionalities to code with. Today we are going to go through some of best ways to reverse an array in JavaScript.
Reversing an array will completely reverse all its elements from last to First or in opposite order.
For example:
const arrayObj = [1,2,3,4,5,6,7,8,9,10];
we must get this output after reversing the array
output: [10,9,8,7,6,5,4,3,2,1];
Using Reverse Method
This one method is used to change the sequence of elements in an array and then return reversed sequence example:
let data = [11, 12, 13, 14, 15, 16, 17];
console.log(data.reverse());
output:
[17, 16, 15, 14, 13, 12, 11]
Things to note:- Changes the original array orders
- Supported in every browser
- No parameters
Using For Loop
There is another way to reverse an array with for loop, With the for loop we can reverse an array by setting a loop from last element to first and then save into a new array. See the example
function reverseArr(input) {
var newArr = new Array;
for(var i = input.length-1; i >= 0; i--) {
newArr.push(input[i]);
}
return newAr;
}
let data = [1, 2, 3, 4, 5, 6, 7, 8];
var reversedArr = reverseArr(data);
console.log(reversedArr);
output:
[8, 7, 6, 5, 4, 3, 2, 1]
Using Spread and reverse
JavaScript Spread operator refers to use ... to expand an iterable object into a list of arguments. We can use this expression to directly apply to reverse method of JavaScript.
For example:
let dataArray = ['one', 'two', 'three', 'four'];
let newArray = [...dataArray].reverse();
console.log(dataArray); // ['one', 'two', 'three', 'four']
console.log(newArray); // [ 'four', 'three', 'two', 'one' ]
Using map and unshift
we can use this both function to reverse an array like this:
var dataArr = [11, 22, 33, 44, 55, 66];
var newArr = [];
dataArr.map((item) => {
newArr.unshift(item);
});
console.log(newArr);
output:
[66, 55, 44, 33, 22, 11]
Using Spread and Reduce
The reducer function takes 4 arguments:
- Accumulator
- Current Value
- Current Index
- Source Array
Using reduce() function we can reverse an array where Accumulator get assigned the value that returned from the reduce function so that using Spread function we can create a new array in reversed.
let dataAr = [1, 2, 3, 4, 5, 6, 7, 8];
let newArr = dataArr.reduce((accumulator, currentValue) => {
return [currentValue,...accumulator];
},[]);
console.log(newArr);
output: [8, 7, 6, 5, 4, 3, 2, 1]
Summary
In this section, we saw how we can reverse an array using top 5 methods. Other then them we have another ways to reverse an array but these can make the requirements fulfilled.
0 Comments