iT邦幫忙

2023 iThome 鐵人賽

DAY 7
0
Software Development

LELECOCODE 每一天系列 第 7

Day7 : Leetcode 小挑戰,30 Days of JavaScript

  • 分享至 

  • xImage
  •  

Day 7:Array Reduce Transformation

Given an integer array nums, 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 init.

Please solve it without using the built-in Array.reduce method.

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

}

Example 1:
Input:
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr; }
init = 0
Output: 10

Example 2:
Input:
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr * curr; }
init = 100
Output: 130

Example 3:
Input:
nums = []
fn = function sum(accum, curr) { return 0; }
init = 25
Output: 25


開始有點煩了,但跟昨天的有點類似
本來還寫了 if 來判斷,但看了別人的解法,覺得多此一舉,改為以下

var reduce = function(nums, fn, init) {
  let count = init;
    
  for (let i = 0; i < nums.length; i++) {
    count = fn(count, nums[i]);
  }
    
  return count;
};

上一篇
Day6 : Leetcode 小挑戰,30 Days of JavaScript
下一篇
Day 8 : Leetcode 小挑戰,30 Days of JavaScript
系列文
LELECOCODE 每一天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言