Sum to number javascript

Sum to number javascript

Last updated: Jan 2, 2023
Reading time · 2 min

banner

# Sum all the Digits in a Number using JavaScript

To sum all the digits in a number:

  1. Convert the number to a string.
  2. Use the split() method to split the string into an array of digits.
  3. Use the reduce() method to sum up all the digits in the array.
Copied!
function getSumOfDigits(num) return String(num) .split('') .reduce((accumulator, digit) => return accumulator + Number(digit); >, 0); > console.log(getSumOfDigits(1)); // 👉️ 1 console.log(getSumOfDigits(123)); // 👉️ 6 console.log(getSumOfDigits(1234)); // 👉️ 10

The function takes a number as a parameter and returns the sum of the digits of the number.

We used the String() constructor to convert the number to a string and used the String.split() method to split the string into an array of digits.

Copied!
console.log('1'.split('')); // 👉️ ['1'] console.log('123'.split('')); // 👉️ ['1', '2', '3'] console.log('1234'.split('')); // 👉️ ['1', '2', '3', '4']

We passed an empty string to the String.split() method to split the string on each character (digit).

The last step is to use the Array.reduce method to iterate over the array.

Copied!
function getSumOfDigits(num) return String(num) .split('') .reduce((accumulator, digit) => return accumulator + Number(digit); >, 0); > console.log(getSumOfDigits(1)); // 👉️ 1 console.log(getSumOfDigits(123)); // 👉️ 6 console.log(getSumOfDigits(1234)); // 👉️ 10

The function we passed to the reduce() method gets called with each element (digit) in the array.

The second argument we passed to the method is the initial value for the accumulator variable.

On each iteration, we return the sum of the accumulator and the current digit.

Whatever we return from the callback function gets passed as the accumulator on the next iteration.

Once the reduce() method iterates over the entire array, we have the sum of all the digits in the number.

Alternatively, you can use a while loop.

# Sum all the Digits in a Number using a while loop

This is a three-step process:

  1. Initialize a sum variable to 0 .
  2. Use the modulo operator to get each digit of the number.
  3. Add each digit to the sum variable.
Copied!
function getSumOfDigits(num) let initialNumber = num; let sum = 0; while (initialNumber) sum += initialNumber % 10; initialNumber = Math.floor(initialNumber / 10); > return sum; > console.log(getSumOfDigits(1)); // 👉️ 1 console.log(getSumOfDigits(123)); // 👉️ 6 console.log(getSumOfDigits(1234)); // 👉️ 10

We used a while loop to iterate for as long as the initialNumber variable stores a truthy value (not 0 ).

On each iteration, we use the modulo % operator to get the remainder of dividing the number by 10 .

Copied!
console.log(1234 % 10); // 👉️ 4 console.log(123 % 10); // 👉️ 3 console.log(12 % 10); // 👉️ 2

The expression returns the last digit of the number.

The next step is to reassign the initialNumber variable so that the last digit is removed.

On each iteration, we get the last digit of the number and add it to the sum variable.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How To Sum All The Digits In A Number In JavaScript

Sum all the Digits in a Number in JavaScript

In this article, I will use some built-in methods in JavaScript to sum all the digits in a number in JavaScript. Stay tuned for the next part of the article to see how I will use them.

Sum all the digits in a number in JavaScript

Sum all the digits by For loop

Before sum all the digits by For loop, we have to get the digits of the given number and save it with the toString() and split() method.

toString() method

This method is used to convert numbers to string.

split() method

string.split(separator, maxsplit)
  • separator: is the specified string to split the string. If not passed, the default will be a space.
  • maxsplit: is the number of string separators, if -1 means all instances of string separator appear.
// Create an array to store the digits of Number let numArr = num.toString().split("");

After getting the digits, we sum all the digits by For loop.

function sumAllDigitsNumber(num) < let sum = 0; // Create an array to store the digits of Number let numArr = num.toString().split(""); for (let i = 0; i< numArr.length; i++) < sum += Number(numArr[i]) >return(sum); > console.log(sumAllDigitsNumber(2022));

In the above example, we see that I go through each element of the array that I have obtained via the toString() and split() methods and then add them together to get the sum of the digits.

Sum all the digits by available methods

Similar to the sum of all the digits by For loop method, with this method, we also have to get the digits of the number from which we can calculate their sum.

// Create an array to store the digits of Number let numArr = num.toString().split("");

I use the same command to get the array containing the digits of the number. We will get their sum from that array through the map() and reduce() method.

array.map(function(currentValue, index, arr), thisValue)
  • function: is the function that executes for each element of the array that map calls.
  • currentValue: is the value of the element in the array being called by the map.
  • index: is the address of the element in the array being called by the map.
  • arr: is the array of the element in the array being called by map.
  • thisValue: is the value passed to the default function that is undefined.
let nums = [10,3,5]; console.log(nums); // Sum of nums console.log(nums.map(function(current,index)< return index + ": value*10 = " + current*10>))

reduce() method

array.reduce(function(total,currentValue, currentIndex, arr), initialValue)
  • function: A function runs for each element in the array being called by reduce.
  • total: The return value of the function or the first value of the function.
  • currentValue: The value of the element in the array being called by reducing.
  • currentIndex: The address of the element in the array being called by reduce.
  • arr: Is the array of the element in the array being called by reducing.
  • initialValue: The value passed to be the initial value of the function.
let nums = [10,3,5]; console.log(nums); // Sum of nums console.log("Sum: " + nums.reduce(function(total, currentValue)))

To learn more about these two methods, visit the W3C docs.

Continuing with this article, we implement the sum of all the digits by the methods available here, which map() and reduce() methods are as follows:

function sumAllDigitsNumber(num)< // Create an array to store the digits of a number let numArr = num.toString().split(""); let sum = numArr.map(Number).reduce(function (a, b) , 0); return sum; > console.log(sumAllDigitsNumber(2022));

In this example, I used the map() method to cast an array of digits from string to number, and then we used the reduce() method to calculate their sum, and now we have a number that is the sum of the digits of the given number.

Summary

Above are some ways to sum all the digits in a number in JavaScript. Try to follow along while reading this article. It will help you remember longer. I hope this article helps you and your program. Good luck.

Maybe you are interested:

My name is Tom Joseph, and I work as a software engineer. I enjoy programming and passing on my experience. C, C++, JAVA, and Python are my strong programming languages that I can share with everyone. In addition, I have also developed projects using Javascript, html, css.

Job: Developer
Name of the university: UTC
Programming Languages: C, C++, Javascript, JAVA, python, html, css

Источник

Sum the Digits of a Number in JavaScript

To sum the digits of a number in JavaScript, we can use a for loop which will get each digit from the number and add them together. Here is a quick function that will take a number and then sum it’s digits:

function sumDigits(num)< var sum = 0; var numString = num + ""; for ( var i = 0; i < numString.length; i++ )< sum = sum + Number(numString.charAt(i)); >; return sum; > 

Let’s break down this function line by line.

In our sumDigits() function, we first start out by creating a variable that we will use to help sum up all the numbers, called sum.

We next convert the number into a string.

We then use a for loop to loop through all of the digits in the number. In this for loop, we use the charAt() method to help iterate over each digit in the number. We then add that number to our overall sum.

Finally, we return the value of the sum of the digits of the number.

Let’s see this function in action below.

Sum the Digits of a Number in JavaScript With a Click

To sum up the digits of a number on click using JavaScript, we can combine the function sumDigits() we created above with a click event.

Below we will provide code to let the user input a number, and then use our function to return the results. Here is our simple HTML setup:

Type a number you want to sum the digits of:

Below is the JavaScript code which take the user input using the onkeyup event or the onclick event along with the value property and use our function sumDigits() on that user input and update the results below using the textContent property.

Here is the JavaScript code:

function sumDigits(e) < //If we clicked or pressed enter, run the following code if( e == 'click' || e.keyCode == 13 )< //Get the number the user entered var userNum = document.getElementById("userVal").value; //Use code from our function above var sum = 0; var numString = userNum + ""; for ( var i = 0; i < numString.length; i++ )< sum = sum + Number(numString.charAt(i)); >; //Show the result to the user to the user document.getElementById("results").textContent = sum; > >; 

The final code and output for this example are below:

Type a number you want to sum the digits of:

Type a number you want to sum the digits of:

; document.getElementById("results").textContent = sum; > >;

Hopefully this article has been useful in helping you understand how to sum up the digits of a number in JavaScript.

  • 1. JavaScript Capitalize First Letter of Every Word
  • 2. Convert String to Array in JavaScript
  • 3. Using the getElementsByClassName Method in JavaScript
  • 4. Remove All Instances of Value From an Array in JavaScript
  • 5. JavaScript tanh – Find Hyperbolic Tangent of Number Using Math.tanh()
  • 6. Using JavaScript to Get the Decimal Part of a Number
  • 7. How to Remove All Numbers From String in JavaScript
  • 8. JavaScript continue statement – Skip Iterations in Loop Based on Conditions
  • 9. JavaScript Power Operator
  • 10. How to Convert Radians to Degrees Using JavaScript

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

JavaScript Program To Find Sum Of N Numbers

Let’s start by writing a simple JavaScript function which will loop through numbers from 1to N and calculate the sum. Here is how it looks :

/* ** Method to Find Sum of N Numbers */ function findSum(n)  let result = 0; for(let i = 1; i  n; i++)  result = result + i; > return result > let n = 10; console.log(`Sum of numebers from 1 to $n> is $findSum(n)>`) 

As seen in the above, you iterated from 1 to number N and added the numbers to get the sum. The problem with the above implementation is that as the number gets bigger, so does the number of iterations.

Mathematical Approach To Find Sum Of N Numbers

Using a mathematical approach to find the sum of N numbers may completely remove the use of for loop. Let’s try to address the above problem from a mathematical approach.

The problem that you are trying to solve is :

Let’s assume the sum of the above series to be sum.

sum = 1 + 2 + 3 + 4 + 5 + 6 + …….. + n ——— eq-1

Now let’s reverse the series, and add the numbers backwards which will also give the same sum.

Let’s add the above eq-1 and eq-2 equations.

2(sum) = (n+1) + (n+1) + (n+1) + (n+1) + ……. (n+1)

2(sum) = n times (n+1)

sum = (n times (n+1)) / 2

You can use the above formula to find the sum of N numbers. Now let’s write the JavaScript program which implements the above formula.

function findSumWithFormula(n)  return (n * (n + 1)) / 2 > let n = 10; console.log(`Sum of numbers from 1 to $n> is $findSumWithFormula(n)>`); 

Wrapping It Up

In this tutorial, you learnt about two ways to implement the sum of N numbers using JavaScript. Do let us know your thoughts in the comments below.

Источник

Читайте также:  Compile and execute java class
Оцените статью