settingsAccountsettings
Menusettings

Q: Aggregates (task with advanced JavaScript functions)

+3 votes

Write a JS program that uses a reducer function to display information about an input array.

Input:
You will receive an array of numeric values.

Output:
The output should be the printed on the console. Display the sum of all elements in the array, the value of the smallest, the value of the biggest, the product of all elements and a string of all elements joined together.

Examples:

Sample Input:

[2,3,10,5]

Output:

Sum = 20

Min = 2

Max = 10

Product = 300

Join = 23105


Sample Input:

[5, -3, 20, 7, 0.5]

Output:

Sum = 29.5

Min = -3

Max = 20

Sum = -1050

Join = 5-32070.5

 

asked in JavaScript category by user matthew44

1 Answer

+2 votes

Here is my JavaScript code (solution):

function calcAggregates(arr) {
    arr = arr.map(Number);

    function reduce(arr, func) {
        let result = arr[0];

        for (let i of arr.slice(1)) {
            result = func(result, i);
        }
        return result;
    }

    let sum = reduce(arr, (a, b) => a + b);
    let min = reduce(arr, (a, b) => Math.min(a, b));
    let max = reduce(arr, (a, b) => Math.max(a, b));
    let product = reduce(arr, (a, b) => a * b);
    let join = reduce(arr, (a, b) => String(a) + b);

    console.log(`Sum = ${sum}`);
    console.log(`Min = ${min}`);
    console.log(`Max = ${max}`);
    console.log(`Product = ${product}`);
    console.log(`Join = ${join}`);
}


calcAggregates(["2", "3", "10", "5"]);

 

answered by user mitko
...