iT邦幫忙

2023 iThome 鐵人賽

DAY 5
0
Software Development

LELECOCODE 每一天系列 第 5

Day 5: Leetcode 小挑戰,30 Days of JavaScript

  • 分享至 

  • xImage
  •  

Day 5: Apply Transform Over Each Element in Array

Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element.

The returned array should be created such that returnedArray[i] = fn(arr[i], i).

Please solve it without the built-in Array.map method.

var map = function(arr, fn) {
    let result = [];
    fot(let i = 0; i < arr.length; i++) {
        result.push(fn(arr[i], i));
    }
    return result;
};

Example 1:
Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
Output: [2,3,4]

Example 2:
Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
Output: [1,3,5]

Example 3:
Input: arr = [10,20,30], fn = function constant() { return 42; }
Output: [42,42,42]


雖然還是很簡單,不過開始變得有點囉說了

var map = function(arr, fn) {
    let result = [];
    for(let i = 0; i < arr.length; i++) {
        result.push(fn(arr[i], i));
    }
    return result;
};

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

尚未有邦友留言

立即登入留言