Here's a Code Recipe to keep around if you need to reverse the order of the elements of an array. You can use the array method, "reverse()" ⏪
Trying a new segment called #CodeRecipes. I want to cover questions that I often google. These are recipes that you should definitely keep handy because it's not a matter "if" you use it, but "when" 😉
const benjamin = ['👶','👦', '👨', '👴'];
const benjaminButton = benjamin.reverse();
console.log(benjaminButton);
// ['👴', '👨', '👦', '👶']
Modifies Original Array
One thing to note is that it mutates the original array.
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reverse();
console.log(originalArray); // [ 'c', 'b', 'a' ]
console.log(newArray); // [ 'c', 'b', 'a' ]
How to Reverse Array Without Mutating Original Array
Here are some recipes that won't mutate the original array. Let's take a look 👀
Using slice
and reverse
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.slice().reverse();
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]
Using spread
and reverse
const originalArray = ['a', 'b', 'c'];
const newArray = [...originalArray].reverse();
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]
Using reduce
and spread
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduce((accumulator, value) => {
return [value, ...accumulator]
}, []);
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]
Using reduceRight
and spread
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduceRight((accumulator, value) => {
console.log(value);
return [...accumulator, value]
}, []);
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]
Or using push
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduceRight((accumulator, value) => {
accumulator.push(value);
return accumulator;
}, []);
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]
Community Input
@aminnair: I decided to test another way of thinking this. Here are the results:
with slice and reverse: 83.085ms
With one loop: 309.763ms
Source code and tests are available here
Resources
- MDN Web Docs: reverse
- w3schools: reverse
- Stack Overflow: Reverse array in Javascript without mutating original array
Thanks for reading ❤
Say Hello! Instagram | Twitter | Facebook | Blog | SamanthaMing.com
Top comments (13)
I saw my name a lot here😁😁.
Lol, it’s a good name! Hopefully it’s just Benjamin and not Benjamin button 😂
Lol... just Benjamin😂😂😂
Phew! Cause I don’t think I know a doctor for that otherwise 😂
Good Tips. Something New Learn Today.
Hey Samantha,
I have a question: What is the runtime of Array.reverse() method ?
Thank you 😊
Good Tipps
Thanks! Glad you found it helpful 👏
Some comments may only be visible to logged-in visitors. Sign in to view all comments.