Let’s Check Armstrong Number of n Digits in JavaScript
An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits, each raised to the power of the number of digits in the number itself.
For example, 153 is an Armstrong number because it has three digits, and 1³ + 5³ + 3³ = 153.
Let’s start with defining our function:
The first thing we do; will be to convert the number to a string and split it into an array of digits. (for example: if it is 153, it will be [1,5,3] )
function isArmstrongNumber(number) {
const digits = number.toString().split("");
}
Now we can get the number of digits.
const n = digits.length;
Then we will calculate the sum of the nth power of each digit.
const sum = digits.reduce((acc, digit) => {
return acc + Math.pow(parseInt(digit), n);
}, 0);
We use reduce() method to apply the function to each element in the array, in order to reduce the array to a single value.
The reduce() method is called on the digits array, with an initial value of 0.
The callback function takes two arguments: the acc and the digit. In each iteration, the callback function adds the digit to the acc (accumulator) and returns the new accumulator value. The final result is the sum of all the numbers in the array.
To do this, we first convert the string into the integer with parseInt() method, and with Math.pow(parseInt(digit), n) we calculate the nth power of the digit.
As a last thing, we need to check if the sum is equal to the original number.
If we put everything together, the code will look like as below: