- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Negative number digit sum in JavaScript
We are required to write a JavaScript function that takes in a negative integer and returns the sum of its digits.
For example: If the number is −
-5456
Output
Then the output should be −
5+4+5+6 10
Example
The code for this will be −
const num = -5456; 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
The output in the console −
10
Advertisements