Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
Understanding Absolute Sum
The absolute sum means we convert all negative numbers to positive and then add all elements. For the array [1, -5, -34, -5, 2, 5, 6], we get: 1 + 5 + 34 + 5 + 2 + 5 + 6 = 58.
Method 1: Using Manual Conversion
This approach manually checks each element and converts negative values to positive by multiplying by -1:
const arr = [1, -5, -34, -5, 2, 5, 6];
const absoluteSum = arr => {
let res = 0;
for(let i = 0; i
58
Method 2: Using Math.abs() Alternative
Since we can't use built-in functions, we can create our own absolute function:
const arr = [1, -5, -34, -5, 2, 5, 6];
const absoluteSum = arr => {
let sum = 0;
for(let i = 0; i
58
Method 3: Using Reduce
A more functional approach using array reduce method:
const arr = [1, -5, -34, -5, 2, 5, 6];
const absoluteSum = arr => {
return arr.reduce((sum, num) => {
return sum + (num
58
Comparison
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| Manual Loop | Good | Fast | Longer |
| Conditional Operator | Better | Fast | Shorter |
| Array Reduce | Best | Slower | Shortest |
Conclusion
All three methods calculate the absolute sum without built-in functions. The conditional operator approach offers the best balance of readability and performance for most use cases.
