Kayla Famurewa
Kayla Famurewa

Reputation: 63

Javascript reduce method not returning expected output. What is going wrong here?

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

Upvotes: 3

Views: 444

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

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))

Upvotes: 4

Related Questions