Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 45b31fd

Browse files
Day 5 problem solved
1 parent 332e5ea commit 45b31fd

File tree

1 file changed

+59
-0
lines changed
  • LeetCode/30daysJavaScript/5.Apply_Transform_Over_Each_Element_in_Array

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
3+
4+
5+
Apply Transform Over Each Element in Array
6+
7+
Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element.
8+
9+
The returned array should be created such that returnedArray[i] = fn(arr[i], i).
10+
11+
Please solve it without the built-in Array.map method.
12+
13+
14+
15+
Example 1:
16+
17+
Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
18+
Output: [2,3,4]
19+
Explanation:
20+
const newArray = map(arr, plusone); // [2,3,4]
21+
The function increases each value in the array by one.
22+
Example 2:
23+
24+
Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
25+
Output: [1,3,5]
26+
Explanation: The function increases each value by the index it resides in.
27+
Example 3:
28+
29+
Input: arr = [10,20,30], fn = function constant() { return 42; }
30+
Output: [42,42,42]
31+
Explanation: The function always returns 42.
32+
33+
34+
Constraints:
35+
36+
0 <= arr.length <= 1000
37+
-109 <= arr[i] <= 109
38+
fn returns an integer.
39+
40+
41+
42+
*/
43+
44+
45+
function map(arr: number[], fn: (n: number, i: number) => number): number[] {
46+
const arr2: number[] = [];
47+
48+
for (let i = 0; i < arr.length; i++) {
49+
const ele: number = fn(arr[i], i);
50+
arr2.push(ele);
51+
}
52+
53+
return arr2;
54+
};
55+
56+
const namArr: number[] = [1, 2, 3];
57+
const calFn = (n: number, i: number): number => {
58+
return n + i;
59+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /