[Easy] LeetCode JS 30 - 2626. Array Reduce Transformation

April 30, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2626. Array Reduce Transformation

Question Prompt

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 length of the array is 0, the function should return init. Please solve it without using the built-in Array.reduce method.

// Example 1
Input:
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr; }
init = 0
Output: 10
Explanation:
initially, the value is init=0.
(0) + nums[0] = 1
(1) + nums[1] = 3
(3) + nums[2] = 6
(6) + nums[3] = 10
The final answer is 10.

// Example 2
Input:
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr * curr; }
init = 100
Output: 130
Explanation:
initially, the value is init=100.
(100) + nums[0] * nums[0] = 101
(101) + nums[1] * nums[1] = 105
(105) + nums[2] * nums[2] = 114
(114) + nums[3] * nums[3] = 130
The final answer is 130.

Solutions

Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!

First, define the reduce function with three parameters:

  • nums: The array of elements to be processed.
  • fn: The function to apply to each element and the accumulator
  • init: The initial accumulator value.

Then, initialize the accumulator through let value = init , and iterate through each element (num) in the nums array. In the iteration, apply the fn function to the current accumulator (value) and the current element (num). The result becomes the new accumulator value.

After the loop, returns the final accumulated value after processing all elements.

var reduce = function (nums, fn, init) {
  let value = init;

  for (const num of nums) {
    value = fn(value, num);
  }

  return value;
};
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee