DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Cover image for Array Methods in JS - reverse()
Mysterio
Mysterio

Posted on • Updated on

Array Methods in JS - reverse()

Hello Guys today i will discuss reverse() array method in javascript
reverse() method is used to reverse array elements

Example -
[1,2,3,4,5]
After reversing
[5,4,3,2,1]

Let's get started...

Code Example 1 -

const numberArray = [1,2,3,4,5];
const stringArray = ['A','B','C','D','E'];
const booleanArray = [true,true,false,true,false];
const objectArray = [
  {
  name:"Shubham",
  age:21
  },
  {
  name:"Shivam",
  age:25
  },
  {
  name:"Bharat",
  age:22
  },
]
const mixedArray = [1,2,3,"A","B","C",true,false,
{
   name:"Shivam",
  age:25
}
]



console.log(numberArray.reverse())
console.log(stringArray.reverse())
console.log(booleanArray.reverse())
console.log(objectArray.reverse())
console.log(mixedArray.reverse())
Enter fullscreen mode Exit fullscreen mode

Output -

[ 5, 4, 3, 2, 1 ]
[ 'E', 'D', 'C', 'B', 'A' ]
[ false, true, false, true, true ]
[
  { name: 'Bharat', age: 22 },
  { name: 'Shivam', age: 25 },
  { name: 'Shubham', age: 21 }
]
[ { name: 'Shivam', age: 25 }, false, true, 'C', 'B', 'A', 3, 2, 1 ]

Enter fullscreen mode Exit fullscreen mode
  • As you can see we have reverses the arrays containing number, strings, booleans, objects and mixed.

Code Example 2 - How to reverse a string

const string = "hello"
const stringArray2 = []
for (let i of string){
  stringArray2.push(i)
}
stringArray2.reverse()
let reversedStr = stringArray2.join("").toString()
console.log(newStr)
Enter fullscreen mode Exit fullscreen mode

Output -

olleh
Enter fullscreen mode Exit fullscreen mode
  • As you can see first we have converted the string into array with each character as an element of array then we applied the reverse() method on this array.
  • After that we have used the join("").toString() to again convert the array into string again.

THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank you๐Ÿ‘‡๐Ÿ‘‡ ^^
โ˜• --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo

https://dev.to/shubhamtiwari909/e-quotes-3bng

https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl

Top comments (23)

Collapse
 
joelbonetr profile image
JoelBonetR

Another one, this time with recursion:

/**
 * Reverses a string recursively
 * @param {string} str 
 * @returns {string}
 */
const reverseString = (str) => (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
Enter fullscreen mode Exit fullscreen mode
reverseString("hello") // olleh
reverseString('Hello, how are you?') // ?uoy era woh ,olleH
Enter fullscreen mode Exit fullscreen mode

๐Ÿ˜

Collapse
 
shubhamtiwari909 profile image
Mysterio Author

yeah but i only tried to discuss the inbuilt reverse() array method but this one liner implementation is also cool ๐Ÿ˜Ž

Collapse
 
joelbonetr profile image
JoelBonetR

Say no more:

const reverseStr = (str) => str.split("").reverse().join(""));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ˜‚๐Ÿ˜‚

I'm loving this posts you do on your learning, following up to read more ๐Ÿ˜

Thread Thread
 
shubhamtiwari909 profile image
Mysterio Author

Yeah this one is also good but then I had to explain this also and i am trying to show everything as a beginners perspective so later they can simplify the code on their own and come with these type of one liner solutions ๐Ÿ˜‰
Also I want to explain join and split in a separate posts that's why I didn't explained much about them in this blog ๐Ÿ˜‚๐Ÿ˜‚

Thread Thread
 
frankwisniewski profile image
Frank Wisniewski

seen 1000 times and wrong 1000 times...

const str = 'Hello ๐Ÿ˜Š World';
const reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // 'dlroW ๏ฟฝ๏ฟฝ olleH'
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
joelbonetr profile image
JoelBonetR • Edited on

Yes yees we know, that doesn't mean it's wrong. You don't need to deal with emojist most of the time and when you do, simply

const reverseStr = (str) => [...str].reverse().join('');
Enter fullscreen mode Exit fullscreen mode

There are multiple ways to deal with that ๐Ÿคท๐Ÿปโ€โ™€๏ธ

Thread Thread
 
frankwisniewski profile image
Frank Wisniewski • Edited on

the only correct way: Intl.Segmenter!!

it's not about emojis, it's plain and simple also about characters in other languagesโ€ฆ

dev.to/lukeshiru/comment/20d68

Thread Thread
 
rkallan profile image
RRKallan

Intl.Segmenter is not working with Firefox

Thread Thread
 
frankwisniewski profile image
Frank Wisniewski

use a polyfilll

Thread Thread
 
joelbonetr profile image
JoelBonetR • Edited on

So I tried to break this down a bit

const reverseStr = (str) => [...str].reverse().join('');
Enter fullscreen mode Exit fullscreen mode
reverseStr('๐Ÿ˜hi๐Ÿ˜…hello') // 'olleh๐Ÿ˜…ih๐Ÿ˜'
reverseStr('๐Ÿ˜ะฟั€ะธะฒะตั‚') // 'ั‚ะตะฒะธั€ะฟ๐Ÿ˜'
reverseStr('ๅพ่ผฉใฏ็Œซใงใ‚ใ‚‹๐Ÿฑ') // '๐Ÿฑใ‚‹ใ‚ใง็Œซใฏ่ผฉๅพ'
reverseStr('๐Ÿ˜ฎโ€๐Ÿ’จ') // '๐Ÿ’จโ€๐Ÿ˜ฎ' <-- this is a ZWJ Sequence working properly
// You can also set the `u` flag for Unicode codepoints like that:
"๐Ÿ˜„๐Ÿ˜„".split(/(?:)/u); // [ "๐Ÿ˜„", "๐Ÿ˜„" ]
Enter fullscreen mode Exit fullscreen mode

but this won't work for some ZWJ Sequences (multiple emojis joined with a zero-width joiner character being displayed as a "single emoji") and I was wondering why.

If we look at the Unicode Technical Standard, @lukeshiru you pick the emoji wisely to showcase.

reverseStr('๐Ÿง‘๐Ÿปโ€๐Ÿ’ป') // '๐Ÿ’ปโ€๐Ÿป๐Ÿง‘' <--  this is a ZWJ Sequence working 'wrong'
Enter fullscreen mode Exit fullscreen mode

Actually it's doing "great" reversing the whole thing as it did with

reverseStr('๐Ÿ˜ฎโ€๐Ÿ’จ') // '๐Ÿ’จโ€๐Ÿ˜ฎ'
Enter fullscreen mode Exit fullscreen mode

The issue I think is that the "computer" can't be joined with the "skin tone" and we see this weird symbol because skin tone does not work standalone.

Also I noticed that destructuring has issues with words in hindi as well:

[...'เคนเคพเคฏ เค†เคช เค•เฅˆเคธเฅ‡ เคนเฅˆ'].reverse().join() // 'เฅˆ,เคน, ,เฅ‡,เคธ,เฅˆ,เค•, ,เคช,เค†, ,เคฏ,เคพ,เคน'
Enter fullscreen mode Exit fullscreen mode

Thus it actually works "fine", or as intended from the computation point of view, it's just that we don't have a valid "translation" to show the result, let's say computer &zwj; skin-tone-medium &zwj; human and something similar should be happening with hindi words (and presumably other languages).

Whenever you need to work with ZWJ Sequences or some specific languages, Intl.segmenter is the option because it simply doesn't break those joined unicodes into something "unreadable". And to be precise it doesn't reverse the icons.

If the standard covered symbols to be directional let's say "faceโ€airBlow"๐Ÿ˜ฎโ€๐Ÿ’จ and then "airBlowโ€face" being the opposite (blowing to the left) and also joining the modifiers to the compatible icons (either be right or left), every emoji sequence could be effectively reversed without breaking the "emoji" render.

On the other hand I can't understand -yet- why Firefox is not supporting it, I'll search to see if I can find the reason somewhere.

Do you guys have more detail on that?

Edit: I get some info about it here if you want to check. TL;DR It will be supported in short (theoretically).

Thread Thread
 
shubhamtiwari909 profile image
Mysterio Author

this goes directly above my head ๐Ÿ˜‚๐Ÿ˜‚

Thread Thread
 
lukeshiru profile image
Luke Shiru

Part of your argument is that this:

reverseStr('๐Ÿ˜ฎโ€๐Ÿ’จ') // '๐Ÿ’จโ€๐Ÿ˜ฎ'
Enter fullscreen mode Exit fullscreen mode

Is "doing great", but it stopped being a "single emoji" to be two when reversed, which isn't ideal, if I write "hello๐Ÿ˜ฎโ€๐Ÿ’จ" I expect the returned value to be "๐Ÿ˜ฎโ€๐Ÿ’จolleh" not "๐Ÿ’จโ€๐Ÿ˜ฎolleh", even if those are the "parts" of the emoji reversed. The idea with the good Intl.Segmenter is that it keeps the "segments" of a string intact, which is shown by emojis which are the simplest example, but as you investigated also works with languages that use those kind of characters.

As far as I know, there is not "real world scenario" in which this will be widely useful. Generally strings written by devs are hardcoded, so we can harcode the "reversed" version as well, and dynamically reversing strings aren't a common thing unless you're writing a game of sorts that uses that logic. I generally share Intl.Segmenter not so much as a solution to this particular problem, but more as a consideration that devs should have when writing string manipulation functions with languages other than english. I have the same kind of complaint when folks use String.prototype.toUpperCase instead of String.prototype.toLocaleUpperCase, or when they consider that making the string[0] uppercase is correct in all languages, and stuff like that.

Thread Thread
 
joelbonetr profile image
JoelBonetR

Agree. That's one thing I love of coding. Each little bloody thing you can pick like that, as you go further in detail it has tones of nuances, quirks, things to take care when defining, various ways to reach something similar and so on ๐Ÿ˜…

Thread Thread
 
shubhamtiwari909 profile image
Mysterio Author

Hey Joel i wanted to ask something that is i am a fresher in web development and student also and i am impressed by your knowledge like you know everything in detail
I want to know from where and how can I improve my knowledge and skills like you and can become a better web developer

Thread Thread
 
joelbonetr profile image
JoelBonetR • Edited on

Hey @shubhamtiwari909 actually you've people with tones of knowledge in the community and here in the post, like @lukeshiru who I found involved in many interesting comments and probably others which I may not recognize from other posts/discussions.

My workaround to learn more is to practice as much as I can and learn about stuff to bring new concepts to develop, new features to use and searching for different ways to reach the same to understand the differences so I can know when and where to use one or another.
I'm working as dev since just a decade ago so that's much less experience than many people here.

I learnt a lot in many projects having seasoned seniors next to me that were nice people and shared the knowledge and answering my child-ish questions (I'm always asking for the reason to be of the things and trying to understand the quirks and details) so I try to do the same in both my job and though this community.

In this specific case I knew almost nothing about this topic which is the emojis breaking when using split and I was itchy to know why does this happen so I began looking for information on the Internet, doing tests on my own, searching more with queries based on my test results... till I fulfilled my need for knowledge.

I knew nothing because the lack of experience. Never had to deal with that, and here's where the community adds an important value to the learning process.
Now, my future "me" will know this details if I need to use them.

If this was something more complex to remember I may write a post on that so anytime I need to remember the details of some concept I can come back to my own post and get what I need.

On the other hand some books helped me to understand some things in the past but not everyone likes to read as much.
I'm here because I prefer to read tech stuff than watching someone on YouTube explaining it. It's faster, I can easily copy-paste concepts, keywords to search later on and take my notes easily.

Also I wrote this post which I want to re-write (a second version of it) with the support of a Psychologist in a future.

Hope it helps you in any way :)

Also check the profiles of all that nice people that came to comment and follow the ones with posts that interests you or that may be of interest for your future "you"! ๐Ÿ˜

Best regards

Thread Thread
 
shubhamtiwari909 profile image
Mysterio Author

Thank you for telling me all of this
I asked this question because I had an interview today and the questions were asked about CSS but the questions were very tricky like which tags have an inline display property by default in HTML, What happens when we try to give width and height to "span" tag , etc and i wasn't able to answer those correctly because I didn't know about the in depth details and also these type of questions never came into my mind while learning that's why I asked how to get deep and detailed knowledge about web development
Same happens with Javascript also but i am practicing it practically and with multiple cases so i am getting little bit in good that

Thread Thread
 
joelbonetr profile image
JoelBonetR • Edited on

Well, as I've previously said, the only way is to practice, reading, and writting posts about the topic are also beneficial

You force yourself into a bit of I+D+i, looking at the details a bit in deep, to ensure you don't publish wrong information.

Thread Thread
 
shubhamtiwari909 profile image
Mysterio Author

Thank you for guidance ๐Ÿ˜‰

Thread Thread
 
joelbonetr profile image
JoelBonetR • Edited on

Np. By the way, the question itself was a bit... uggly-ish if they really asked you to name all HTML tags that are display: inline by default.
I can name <span>, maybe <i>... but the trick on the question is that most default values are not in the CSS spec ๐Ÿ˜… are just browser default styling and in certain cases can differ from one to the other.

Edit: adding this list.

Thread Thread
 
shubhamtiwari909 profile image
Mysterio Author

Yeah the questions were trickier and i get confused and then rejected even it was for the internship interview they believed i have the indepth knowledge and when I asked where can I learn all the things in detail then the interviewer said "you can learn these things in the industry while creating projects in a company under your senior guidance"
I was like yeah that's why I applied here to get that guidance and knowledge ๐Ÿ˜‚๐Ÿ˜‚

Thread Thread
 
joelbonetr profile image
JoelBonetR

๐Ÿ˜‚๐Ÿ˜‚๐Ÿ˜‚๐Ÿ˜‚

Collapse
 
mrwensveen profile image
Matthijs Wensveen

One thing to note is that reverse() works in-place (aka destructively). This is important when you pass your array around to other functions or objects. For example:

function logNormal(arr) { console.log(arr); }
function logReverse(arr) { console.log(arr.reverse()); }
const a = [1, 2, 3]

logReverse(a); // [3, 2, 1]
logNormal(a); // [3, 2, 1] (whoops!)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shubhamtiwari909 profile image
Mysterio Author

Yeah it changes the original array

๐ŸŒš Life is too short to browse without dark mode