3
votes

I am working on a codeWars challenge and am unsure why my reduce method isn't returning the expected outcome.

Here are the instructions:

A Narcissistic Number is a number of length n in which the sum of its digits to the power of n is equal to the original number. If this seems confusing, refer to the example below.

Ex: 153, where n = 3 (number of digits in 153) 1³ + 5³ + 3³ = 153

Write a method is_narcissistic(i) which returns whether or not i is a Narcissistic Number.

Here is my solution:

function narcissistic(value) {
  let digits = (value + '').split('').map(Number);
  let narc = digits.reduce((a, c) => a + (c ** digits.length))
  return narc === value;
}

console.log(narcissistic(371))

When I test it with 371, which is a narcissistic number, 341 is returned instead of 371

1
You need to specify the accumulator value as 0. like digits.reduce((a, c) => a + (c ** digits.length),0)Redu

1 Answers

3
votes

If you don't supply an initial value, the 1st item is used as the initial value, and it's not multiplied. Set the initial value to be 0.

function narcissistic(value) {
  let digits = (value + '').split('').map(Number);
  let narc = digits.reduce((a, c) => a + (c ** digits.length), 0)
  return narc === value;
}

console.log(narcissistic(371))