

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum a negative number (negative and positive digits) - JavaScript
We are required to write a JavaScript function that takes in a negative integer and returns the sum of its digits
For example −
-234 --> -2 + 3 + 4 = 5 -54 --> -5 + 4 = -1
Let’s write the code for this function −
Example
Following is the code −
const num = -4345; const sumNum = num => { return String(num).split("").reduce((acc, val, ind) => { if(ind === 0){ return acc; } if(ind === 1){ acc -= +val; return acc; }; acc += +val; return acc; }, 0); }; console.log(sumNum(num));
Output
Following is the output in the console −
8
- Related Questions & Answers
- Reversing negative and positive numbers in JavaScript
- Negative number digit sum in JavaScript
- Java Program to convert positive int to negative and negative to positive
- Counting number of positive and negative votes in MySQL?
- Python - Sum negative and positive values using GroupBy in Pandas
- How to convert a negative number to a positive one in JavaScript?
- Positive Testing and Negative Testing with Examples
- How to print positive and negative infinity values in JavaScript?
- Implement Bubble sort with negative and positive numbers – JavaScript?
- Positive, negative and zeroes contribution of an array in JavaScript
- Java Program to Check Whether a Number is Positive or Negative
- Program to check if a number is Positive, Negative, Odd, Even, Zero?
- Python Program to Check if a Number is Positive, Negative or 0
- What are the positive and negative impacts of a working mother?
- Python program to count positive and negative numbers in a list
Advertisements