2626. Array Reduce Transformation
On this page, we will discuss LeetCode Problem 2626: Array Reduce Transformation. This problem challenges your understanding of function application, iteration, and accumulator logic.
📄 Problem Statement
Given an integer array nums, a reducer function fn, and an initial value init, return the final result obtained by executing the fn function on each element of the array, sequentially, passing in the return value from the calculation on the preceding element.
This result is achieved through the following operations:
val = fn(init, nums[0]),
val = fn(val, nums[1]),
val = fn(val, nums[2]),
... until every element in the array has been processed.
The ultimate value of val is then returned. If the array is empty, return init.
Note: Solve this without using the built-in Array.reduce method.
💡 Example
Input:
nums = [1, 2, 3, 4]
fn = function sum(acc, curr) { return acc + curr; }
init = 0
Output: 10
🧠 Explanation
This problem tests your knowledge of accumulator-based logic. You must loop through the array and apply the reducer function fn to each item, carrying forward the updated result in each iteration.
The first call is fn(init, nums[0]), then the result of that becomes the first argument for the next call: fn(previousResult, nums[1]), and so on.
If nums is empty, you simply return init without any function calls.
✅ Your Solution
var reduce = function(nums, fn, init) {
let newInit = init;
for(let i = 0; i < nums.length; i++){
newInit = fn(newInit, nums[i]);
}
return newInit;
};