Alternate addition multiplication in an array - JavaScript

We are required to write a JavaScript function that takes in an array of numbers and returns the alternative multiplicative sum of the elements.

For example, if the array is:

const arr = [1, 2, 4, 1, 2, 3, 4, 3];

Then the output should be calculated like this:

1*2 + 4*1 + 2*3 + 4*3
2 + 4 + 6 + 12

And the final output should be:

24

How It Works

The algorithm pairs consecutive elements starting from index 0. Each pair is multiplied together, then all products are summed. If the array has odd length, the last element is paired with 1.

Array: [1, 2, 4, 1, 2, 3, 4, 3] Pairs: (1,2) (4,1) (2,3) (4,3) Products: 2 + 4 + 6 + 12 Result: 24

Example

const arr = [1, 2, 4, 1, 2, 3, 4, 3];

const alternateOperation = arr => {
    const productArr = arr.reduce((acc, val, ind) => {
        if (ind % 2 === 1) {
            return acc;
        }
        acc.push(val * (arr[ind + 1] || 1));
        return acc;
    }, []);
    return productArr.reduce((acc, val) => acc + val);
};

console.log(alternateOperation(arr));
24

Step-by-Step Breakdown

const arr = [1, 2, 4, 1, 2, 3, 4, 3];

const alternateOperation = arr => {
    console.log("Original array:", arr);
    
    const productArr = arr.reduce((acc, val, ind) => {
        if (ind % 2 === 1) {
            return acc; // Skip odd indices
        }
        const product = val * (arr[ind + 1] || 1);
        console.log(`Pair (${val}, ${arr[ind + 1] || 1}) = ${product}`);
        acc.push(product);
        return acc;
    }, []);
    
    console.log("Products array:", productArr);
    const sum = productArr.reduce((acc, val) => acc + val);
    console.log("Final sum:", sum);
    return sum;
};

alternateOperation(arr);
Original array: [ 1, 2, 4, 1, 2, 3, 4, 3 ]
Pair (1, 2) = 2
Pair (4, 1) = 4
Pair (2, 3) = 6
Pair (4, 3) = 12
Products array: [ 2, 4, 6, 12 ]
Final sum: 24
24

Alternative Implementation

Here's a more direct approach using a simple loop:

const alternateOperationSimple = arr => {
    let sum = 0;
    for (let i = 0; i 

24

Edge Cases

// Empty array
console.log("Empty array:", alternateOperation([]));

// Single element
console.log("Single element:", alternateOperation([5]));

// Odd length array
console.log("Odd length:", alternateOperation([2, 3, 4]));
Empty array: 0
Single element: 5
Odd length: 10

Conclusion

The alternate multiplication approach pairs consecutive elements, multiplies each pair, and sums the results. For odd-length arrays, the last unpaired element is multiplied by 1.

Updated on: 2026-03-15T23:18:59+05:30

284 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements