44 ms Beats 69.74%
IntuitionThe problem requires applying a function cumulatively to each element of an array, starting with an initial value. This is essentially a reduction oper
# Intuition
The problem requires applying a function cumulatively to each element of an array, starting with an initial value. This is essentially a reduction operation, where we "reduce" the array to a single value.

# Approach
We can iterate through the `nums` array and apply the provided function `fn` to the current accumulated value (`ans`) and the current element. We initialize the accumulated value with `init`. In each iteration, we update `ans` with the result of `fn(ans, nums[i])`. Finally, we return the accumulated value `ans`.

# Complexity
- Time complexity:
$$O(n)$$
where *n* is the length of the `nums` array. We iterate through the array once.

- Space complexity:
$$O(1)$$
We use a constant amount of extra space, regardless of the input size.

# Code
```javascript []
/**
 * @param {number[]} nums
 * @param {Function} fn
 * @param {number} init
 * @return {number}
 */
var reduce = function(nums, fn, init) {
  let ans = init;
  for(let i = 0;i<nums.length;i++){
    ans  = fn(ans, nums[i]);
  }
  return ans;
};
['JavaScript']