What is the solution for finding the digit root?

I'm encountering some difficulty with a specific challenge and could use some clarification. Thank you in advance. The task involves finding the sum of numbers within an array, such as:

  1. 16 --> 1 + 6 = 7
  2. 942 --> 9 + 4 + 2 = 15
  3. 15 --> 1 + 5 = 6

....and so on.

My current code only works for finding the sum of two numbers.

function digital_root(n) {
    const arrayOfDigits = Array.from(String(n), Number);

    let sum = arrayOfDigits.reduce(function (memo, val) {
        return memo + val;
    });

    return sum;
}

Answer №1

A suggestion is to attempt a recursive call with the base condition of checking if the number has only one digit

function calculateDigitalRoot(n) {
  if (n < 10) {
    return n
  } else {
    const arrayOfDigits = Array.from(String(n), Number)

    let sum = arrayOfDigits.reduce(function(memo, val) {
      return memo + val
    })

    return calculateDigitalRoot(sum)
  }
}

console.log(calculateDigitalRoot(16))
console.log(calculateDigitalRoot(942))

Answer №2

    function calculateDigitalRoot(num) {
const arrayDigits = Array.from(String(num), Number);

let total = arrayDigits.reduce(function(previousValue, currentValue){

return previousValue + currentValue;
});
if(total<10)
return total;
else
return calculateDigitalRoot(total);

 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The code is functional with regular arrays, however, it does not support multidimensional arrays

Currently, I am working on developing a Holdem hand evaluator which requires me to create a function that calculates the number of possible combinations of 5 cards from a selection of 7 cards. I have successfully written the "pickNofSet()" function to achi ...

Tips for extracting nested JSON data and generating a streamlined JSON in Snowflake

Here is the structure of my current JSON object: -- Creating a sample table create or replace table json_example(v variant); -- Inserting a sample JSON record insert into json_example select parse_json( '[ { "key": "va ...

What is the best approach for extracting an object into the context of a function?

Hey there! I came across this interesting piece of code... function a(values) { for (var key in values) { if (!values.hasOwnProperty(key)) { continue; } this[key] = values[key]; } } a({ 'example': 'va ...

Activate Lottie animation upon scrolling

I recently created a unique lottie animation and successfully integrated it into my Nuxt project. I am now looking for the most effective way to manage the animation's behavior as the user scrolls through the page. I noticed that the component has an ...

Is there a way to dynamically set a database path in Express.js depending on the user's login status?

I have a backend service that serves as the primary entry point for my web application, where I want to dynamically allocate a database path based on user login. While I understand that this solution may not be scalable in the long run, I plan to use it fo ...

Guide on transforming an array into a collection of objects

Could someone please help me with converting this array? const myArr = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'] I want to transform it into an object structure like this: { lorem:{ ipsum:{ ...

Why won't disabling a Javascript checkbox also grey out the associated label in ASP.NET?

My current challenge involves using JavaScript to disable checkboxes in a checkbox list. The code snippet I am working with looks like this: var objItem = document.getElementById("<%= resCBL.ClientID %>"); var checkBoxes = objItem.getElementsByTagN ...

Checking if the Cursor is Currently Positioned on a Chart Element in Word Addin/OfficeJS

I am looking for a way to determine if the document cursor is currently positioned inside of a Chart element using the Microsoft Word API. My current application can successfully insert text, but when I attempt to insert text into the Chart title, it ends ...

Stopping video playback when hovering over it

Can anyone help me modify this code so that a video plays only when hovering over it, and stops playing once the hover ends? What changes should I make to the JavaScript portion of the code for this functionality? <div class="padding-box height-40"&g ...

Guide on implementing tail.select in a VueJS project

As a newcomer to VueJS, I am facing issues with using the tail.select plugin in my VueJS project. Even though I have imported the plugin in my main.js file using import 'tail.select' When I try to call tail.select(".select") in the mounted hook ...

Easiest method for creating an array literal within MySQL

Is there a more efficient way to retrieve the array [1,2,3] in MySQL without having to create a table using CTE and then grouping it? I attempted to achieve this using the following query: SELECT '1', [1,2,3] MySQL '8.0.20' Error Co ...

What is the best way to ensure that an mp3 file plays seamlessly across all pages?

Does anyone know how to ensure an mp3 file plays continuously across all pages using webform asp.net? If you have any solutions, please let me know. jQuery('#main .jp-jplayer').each(function(index) { var i = index+1; var ...

dimension of an array

Can the length of an array be determined without utilizing sizeof($array) or count($array)? ...

Saving customer responses in an array that does not begin at index 0

In the given code snippet, there seems to be a problem in OPTION 2 where if the user specified Store = 1, the item details get overwritten in item[0] instead of being stored in item[7]. The item is located in the constructor method of another class. I am l ...

Adjust the height to match the shortest sibling child div height

In my layout, I have multiple rows with each row containing multiple columns. Within each column, there is a div and a paragraph - the div contains an image. My goal is to set the div with the class cover-bg to the lowest height of cover-bg in the same row ...

Tips for efficiently loading an angular controller and template at the same time through a single HTTP request

I am currently utilizing angularjs and am interested in loading parts of a page that I organize as "components". Each component includes its own controller, template, directives, and additional assets like CSS. My goal is to load all of these components on ...

What is the best way to search through an array of dictionaries to locate a specific value?

Here is a dictionary I am working with: let object = [[String : AnyObject]]() /* { "allProducts":[ { "productDetails":[ { "productName":"My product which I am unable to get by NSPredicate." } ] } ] } */ ...

Transforming the appearance of the menu element in Vue using transitions

In my Vue app, I have this SCSS code that I'm using to create a smooth transition effect from the left for a menu when the isVisible property is set to true. However, I am encountering an issue where the transition defined does not apply and the menu ...

Preventing an RxJS Observable interval: A step-by-step guide

I am facing a unique scenario where I am using an RxJS interval, but I might need to abruptly stop it at any point. I thought there would be a simple method like cancel() or stop() similar to clearTimeout for intervals. Is there a way to stop an interval o ...

What is the best way to divide an index in an array into two separate parts in order to ensure that neither part contains an odd or even number?

When verifying roomNumber[i], I must ensure that BOTH digits (assuming it is two-digit) are neither even nor odd. The number can only be accepted if this condition is met. Furthermore, I need to validate that the second digit is greater than or equal to ...