Users Online

· Guests Online: 110

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Reverse in JavaScript

Reverse in JavaScript

Reverse in JavaScript

Introduction to Reverse in JavaScript

JavaScript contains a built-in function called reverse(), which is used to reverse an array or a string. We can also reverse a number through various methods. Either we could store a number in the form of an array or a string and reverse the array using the built-in function, or we could reverse a number using loops (for, while, do-while, etc.). We would be discussing how to reverse an array, string, or a number in javascript in the following article.

Logic to find Reverse in JavaScript

Let us take, for instance, that we want to reverse a number entered by a user in javascript. Reversing a number can also be named as palindrome implementation.

The program will ask you to enter a number and will reverse the number for you. This can be performed in various languages as considered an important concept.

1. For reversing using the built-in function

We can reverse a number either by arrow function or by regular function.

Regular function needs to be given with an explicit value that will be returned as an output, whereas Arrow functions return an implicit value in nature.

Piece of code written using an Arrow function

const reverse =number=>parseFloat(number.toString().split('').reverse().join(''))*Math.sign(number)

Solving using a Regular Function

function reverse(number) {
return (
parseFloat(
num
.toString()
.split('')
.reverse()
.join('')
) * Math.sign(number)
)
}

The number.toString() converts the input number into a data type called a string. Then, the number.split(‘’) converts the String into an Array of characters. The number.reverse(), If the numbers are arranged in order, then this function reverses the items in an array according to the reverse order.

number.join(‘’), This joins the reversed characters to form a single string data type.

parseFloat(number) converts the number ‘number’ into a float from a String. The point to be noted here is that the parseFloat function runs in the end on the reversed number and removes any leading zeroes (even though it is on the first line of the function).

The number * Math.sign(number) helps multiply a number with the preceding sign of the original input given.

2. For reversing the Number using a Loop

<script language='javascript'>
Reverse = function(num) {
var reversed_number = 0;
while (num != 0) {
reversed_number *= 10;
reversed_number += number % 10;
num -= num % 10;
num /= 10;
}
return reversed_number;
}
</script>
<body>
<input type= 'text' id='string'/>&nbsp;<input type='button' value='text' onclick='alert("reversed = " +Reverse(document.getElementById("string").value);'/>
</body>

This method would involve the use of a modulus (%) operator. The reverse function contains a loop that runs until the number (entered by the user) becomes 0. The value will be set to zero in the starting and then gets multiplied by ten consecutively. The number is then increased by the number mod 10.  The original number (which the user entered) will decrease by the number mod 10 every time this transaction occurs. As the final step to complete one inner loop, the number is divided by ten.

However, if the number entered by the user is a decimal number, then adjust the number to make it an integer and follow the same steps as mentioned in the above paragraph; at the end, adjust the reversed result for the decimal.

We use Math.pow() with a base of 10 and an exponent to do the same. This is a standard math function taken from the Javascript standard library.

rev = func(num) {
var newrev = 0;
var exp = num.indexOf('.');
if (exp !== -1) {
num *= Math.pow(10, num.length – exp – 1);
}
while (num != 0) {
newrev *= 10;
newrev += num % 10;
num -= num % 10;
num /= 10;
}
if (exp !== -1) {
newrev /= Math.pow(10, exp);
}
return newrev;
}

Reversing an array

Here are the following example mention below

Example #1

<html>
<head>
<title>This is JAVASCRIPT Array reversing Method</title>
</head>
<body>
<script type = "text/javascript">
var test_arr = [0, 1, 2, 3]. reverse();
document.write("The reversed array is : " + test_arr );
</script>
</body>
</html>

Output:

The reversed array is: 3, 2, 1, 0

The test_arr.reverse() is used for the reversal of an array. The first element becomes the last element, and vice versa. Thus, this method changes the original array. However, you can also reverse an array without modifying the original array as well.

Example #2

var origArray = [10,20,30,40,50];
var reverse = function(array){
var origArray = array;
var newArray = [];
for (var i = origArray.length-1; i>=0; i--)
{
newArray.push(origArray [i])
}
return newArray
}
reverse(origArray)

A new array is created, and the new array elements are pushed in the

reverse order of that of the first array (which is to be reversed). Thus, the original array

remained unmodified, and the new array will be formed.  Using this code will consume more memory in the system, so it is less space-efficient but gives a chance to save the original number for reference. This method can be used if we want the original number in place for us.

Reversing a String

Below is the way to reverse a string in javascript.

function revString(str) {
var splitString = str.split("");
var revArray = splitString.reverse();
var joinArray = revArray.join("");
return joinArray;
}
revString("Test");

Output:

tseT

The split() function splits the string into an array of strings by separating the string into small multiple substrings. The array of substrings is reversed using the reverse() function, and then a new string is created by concatenating all of the elements in an array using the join() method.

Reversing a number using While loop

Here are the following example mention below

Example

//reverse_number.html
<!DOCTYPE HTML>
<html>
<title>reverse_number.html</title>
<script type ="text/javascript">
function revNum()
{
var number = prompt("Please enter the number which needs to be to be reveresed :", " ");
var n= number;
var rev = 0, remaining;
while (n>0)
{
remaining = n % 10;
rev = rev * 10 + remaining ;
n = Math.floor(n/10);
}
document.write("The original input number is : " +number+ " <br/> The reverse of input number is : " +rev+ "\n");
}
</script>
<body onload="revNum();">
<body>
</html>

Output:

Reverse in Javascript 1

Reverse in Javascript 2

Conclusion – Reverse in JavaScript

Javascript contains a built-in function to reverse an array or string. We could reverse a number either by using the function or by using a loop. The numbers can also be converted into arrays or strings; then, the same method can be applied to reverse them, as can be applied to arrays and strings.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.71 seconds
10,828,188 unique visits