Sobes.tech
Junior — Middle

What is the purpose of the reduce function in programming?

sobes.tech AI

Answer from AI

The reduce function is used for sequentially processing elements of a collection (such as an array) to reduce them to a single value. It takes an accumulator and the current element, applies a function to them, and returns the updated accumulator. This is useful for summing, multiplying, merging, or other operations where you need to obtain a final result from a set of data.

Example in Swift:

let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(0) { accumulator, current in
    accumulator + current
}
print(sum) // Outputs 15

Here, reduce adds up all the numbers in the array, starting from 0.

What is the purpose of the reduce function in… - sobes.tech