3
06/11/2024 10:59 am
Topic starter
Write a JS program that performs and outputs different operations on an array of elements. Implement the following operations:
- Sum(ai) - calculates the sum all elements from the input array
- Sum(1/ai) - calculates the sum of the inverse values (1/ai) of all elements from the array
- Concat(ai) - concatenates the string representations of all elements from the array
The input comes as an array of number elements
Examples:
Input:
[1, 2, 3]
Output:
6
1.8333
123
Input:
[2, 4, 8, 16]
Output:
30
0.9375
24816
The output should be printed on the console on a new line for each of the operations.
1 Answer
1
06/11/2024 11:00 am
Here is my JS code:
function aggregateElements(input) {
let elements = input.map(Number);
aggregate(elements, 0, (a, b)=>a + b);
aggregate(elements, 0, (a, b)=>a + 1 / b);
aggregate(elements, "", (a, b)=>a + b);
function aggregate(arr, initVal, func) {
let val = initVal;
for (let i = 0; i < arr.length; i++) {
val = func(val, arr[i]);
}
console.log(val);
}
}
aggregateElements([10, 20, 30]);
