
- 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
Absolute sum of array elements - 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
- Related Articles
- Taking the absolute sum of Array of Numbers in JavaScript
- Thrice sum of elements of array - JavaScript
- Sum of distinct elements of an array - JavaScript
- Consecutive elements sum array in JavaScript
- Sum of distinct elements of an array in JavaScript
- Array element with minimum sum of absolute differences?
- Absolute Values Sum Minimization in JavaScript
- Maximum sum of n consecutive elements of array in JavaScript
- Finding sum of alternative elements of the array in JavaScript
- JavaScript Sum odd indexed and even indexed elements separately and return their absolute difference
- Finding desired sum of elements in an array in JavaScript
- Sum all similar elements in one array - JavaScript
- Sum identical elements within one array in JavaScript
- Sum of all the non-repeating elements of an array JavaScript
- Alternating sum of elements of a two-dimensional array using JavaScript

Advertisements