
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Absolute Sum of Array Elements in JavaScript
We are required to write a JavaScript function that takes in an array with both positive and negative numbers and returns the absolute sum of all the elements of the array.
We are required to do this without taking help of any inbuilt library function.
For example: If the array is −
const arr = [1, -5, -34, -5, 2, 5, 6];
Then the output should be −
58
Example
Following is the code −
const arr = [1, -5, -34, -5, 2, 5, 6]; const absoluteSum = arr => { let res = 0; for(let i = 0; i < arr.length; i++){ if(arr[i] < 0){ res += (arr[i] * -1); continue; }; res += arr[i]; }; return res; }; console.log(absoluteSum(arr));
Output
Following is the output in the console −
58
Advertisements