Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Squaring every digit of a number using split() in JavaScript
We are required to write a JavaScript function that takes in a number as the first and the only argument. The function should then square every digit of the number, append them and yield the new number.
For example −
If the input number is −
const num = 12349;
Then the output should be −
const output = 1491681;
because '1' + '4' + '9' + '16' + '81' = 1491681
How It Works
The solution uses split('') to convert each digit into an array element, then squares each digit and concatenates the results:
- Convert the number to a string using
String(num) - Split the string into individual digits using
split('') - Square each digit and concatenate to build the result
- Convert the final string back to a number
Example
The code for this will be −
const num = 12349;
const squareEvery = (num = 1) => {
let res = '';
const numStr = String(num);
const numArr = numStr.split('');
numArr.forEach(digit => {
const square = (+digit) * (+digit);
res += square;
});
return +res;
};
console.log(squareEvery(num));
1491681
Alternative Approach Using map()
You can achieve the same result using map() and join():
const squareEveryMap = (num) => {
return +String(num)
.split('')
.map(digit => digit * digit)
.join('');
};
console.log(squareEveryMap(12349));
console.log(squareEveryMap(567));
1491681 254649
Step-by-Step Breakdown
Let's trace through the process with number 123:
const num = 123;
console.log("Original number:", num);
const numStr = String(num);
console.log("As string:", numStr);
const digits = numStr.split('');
console.log("Split digits:", digits);
const squares = digits.map(digit => digit * digit);
console.log("Squared digits:", squares);
const result = squares.join('');
console.log("Joined result:", result);
console.log("Final number:", +result);
Original number: 123 As string: 123 Split digits: [ '1', '2', '3' ] Squared digits: [ 1, 4, 9 ] Joined result: 149 Final number: 149
Conclusion
The split('') method effectively converts each digit into an array element, making it easy to process and square individual digits. This approach works well for transforming numbers digit by digit in JavaScript.
