May 10, 2024

Viiisit [LeetCode] - 2626. Array Reduce Transformation

#javascript

keep learning, keep coding!

Problem - Array Reduce Transformation

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.

翻譯蒟蒻

問題要求我們給定一個整數數組、一個縮減函數和一個初始值。需要按照指定的順序,對數組中的每個元素依次應用這個函數,每次的計算結果會作為下一次計算的參數。最後返回整個過程的最終結果。(不能使用內置的 Array.reduce 方法)


Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
let val = init;
for (let i = 0; i < nums.length; i++) {
val = fn(val, nums[i]);
}
return val;
};

LeetCode 傳送門 - Array Reduce Transformation