Array Reduce Transformation | #2626 | LeetCode Solution

Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode

Problem : Array Reduce Transformation | #2626 | LeetCode

Given an integer array `nums` and a reducer function `fn`, and an initial value `init`, return a reduced array.

A reduced array is created by applying the following operation: 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 final value of `val` is returned.

If the length of the array is `0`, it should return `nit`.

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


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:


nums = [1,2,3,4]

fn = function sum(accum, curr) { return accum + curr * curr; }

init = 100

Output: 130


initially, the value is init=100.

(100) + nums[0]^2 = 101

(101) + nums[1]^2 = 105

(105) + nums[2]^2 = 114

(114) + nums[3]^2 = 130

The final answer is 130.

Example 3:


nums = []

fn = function sum(accum, curr) { return 0; }

init = 25

Output: 25

Explanation: For empty arrays, the answer is always init.



     * @param {number[]} nums

     * @param {Function} fn

     * @param {number} init

     * @return {number}


    var reduce = function (nums, fn, init) {

        var val = init;

        for (let i = 0; i < nums.length; i++) {

            val = fn(val, nums[i])


        return val



Let's break down the code step by step:

1. The code defines a function called `reduce`, which is similar in concept to JavaScript's built-in `Array.prototype.reduce` method. It takes three parameters:

   - `nums`: An array of numbers.

   - `fn`: A function that will be used to reduce the array.

   - `init`: An initial value that serves as the starting point for the reduction.

2. Inside the `reduce` function, a variable `value` is declared and initialised with the value of `init`. This variable will be used to accumulate the result of the reduction operation.

3. The function enters a `for` loop that iterates through each element of the input array `nums`. The loop is controlled by the variable `i`, which starts at 0 and goes up to the length of the array.

4. Inside the loop, the `fn` function is called with two arguments: the current value of `val` (which starts as `init`) and the current element of the array `nums[i]`. The purpose of this call is to allow the `fn` function to operate on the current value and element and return a new value that will become the updated value of `val`.

   - `val = fn(val, nums[i])`: This line assigns the result of `fn(val, nums[i])` back to `val`, effectively updating `val` with the result of the function call.

5. The loop continues to iterate through the array, and the `fn` function is applied iteratively to each element in the array, updating the `val` variable in each iteration.

6. After the loop has processed all elements in the input array `nums`, the `val` variable contains the result of the reduction operation.

7. Finally, the `val` variable, which now holds the reduced value, is returned as the result of the `reduce` function.

In summary, the `reduce` function takes an array, a reduction function (`fn`), and an initial value (`init`). It iterates through the array, applying the reduction function to each element and accumulating the result in the `val` variable. The final `val` value represents the result of reducing the array according to the logic defined in the `fn` function.

Related Blogs
Arrow Functions in JavaScript | ES6
Author: neptune | 26th-Mar-2023
#JavaScript #React.js
In this article, we will explore the syntax and usage of arrow functions in detail, along with some examples...

Different ways to handle state in React applications
Author: neptune | 21st-Jun-2023
#JavaScript #React.js
This article explores different ways to manage states in React, including local component state, context API, and state management libraries like Redux...

Managing Virtual Environments in React JavaScript Projects
Author: neptune | 28th-Jun-2023
#JavaScript #React.js
Virtual environments are a valuable tool in React JavaScript projects as they allow developers to isolate dependencies, manage package versions, and maintain project consistency...

All You Need to Know About Pure Functions & Impure Functions in JavaScript
Author: neptune | 02nd-Apr-2023
#JavaScript #React.js
You should try to use pure functions whenever possible and avoid using impure functions unless necessary...

Is Object Empty | #2727 | LeetCode | JavaScript Solution
Author: neptune | 01st-Sep-2023
#JavaScript #LeetCode
Given an object or an array, return if it is empty...

To Be Or Not To Be | #2704 | LeetCode Solution
Author: neptune | 03rd-Sep-2023
#JavaScript #LeetCode
Write a function that helps developers test their code. It should take in any value and return an object with the following two functions...

Filter Elements from Array | #2634 | LeetCode Solution
Author: neptune | 06th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a filtering function `fn`, return a filtered array `filteredArr`...

Counter | #2620 | LeetCode Solution
Author: neptune | 02nd-Sep-2023
#JavaScript #LeetCode
Given an integer n, return a counter function. This counter function returns n and then n + 1, n + 2, etc...

Counter 2 | #2665 | LeetCode Solution
Author: neptune | 04th-Sep-2023
#JavaScript #LeetCode
Write function 'createCounter' It accept an initial integer 'init' It should return an object with three functions- increment() , decrement(), reset()...

Apply Transform Over Each Element in Array | #2635 | LeetCode Solution
Author: neptune | 05th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element...

Function Composition | #2629 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions...

Add Two Promises | #2723 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
Given two promises `promise1` and `promise2`, return a new `promise`. `promise1` and `promise2` will both resolve with a number...

Allow One Function Call | #2666 | LeetCode Solution
Author: neptune | 11th-Sep-2023
#JavaScript #LeetCode
Given a function `fn`, return a new function that is identical to the original function except that it ensures `fn` is called at most once...

Memoize | #2634 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value...

Chunk Array | #2677 | LeetCode Solution
Author: neptune | 19th-Sep-2023
#JavaScript #LeetCode
Given an array arr and a chunk `size`, return a `chunked` array...

Array Prototype Last | #2619 | LeetCode Solution
Author: neptune | 20th-Sep-2023
#JavaScript #LeetCode
Write code that enhances all arrays such that you can call the `array.last()` method on any array and it will return the last element...

View More