
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Taking the absolute sum of Array of Numbers 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];
Output
Then the output should be −
58
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
58
- Related Articles
- Absolute sum of array elements - JavaScript
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
- Taking part from array of numbers by percent JavaScript
- Converting array of Numbers to cumulative sum array in JavaScript
- Sum of all prime numbers in an array - JavaScript
- Array element with minimum sum of absolute differences?
- Array element with minimum sum of absolute differences in C++?
- Squared and square rooted sum of numbers of an array in JavaScript
- Absolute Values Sum Minimization in JavaScript
- Absolute Difference between the Product of Non-Prime numbers and Prime numbers of an Array?
- Sum array of rational numbers and returning the result in simplest form in JavaScript
- Sum of consecutive numbers in JavaScript
- Non-composite numbers sum in an array in JavaScript
- Program to find sum of absolute differences in a sorted array in Python
- Predict the winner of the game on the basis of the absolute difference of sum by selecting numbers in C++

Advertisements