-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2635-ApplyTransformOverEachElementInArray.js
More file actions
53 lines (44 loc) · 1.39 KB
/
2635-ApplyTransformOverEachElementInArray.js
File metadata and controls
53 lines (44 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 2635. 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.
// Example 1:
// Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
// Output: [2,3,4]
// Explanation:
// const newArray = map(arr, plusone); // [2,3,4]
// The function increases each value in the array by one.
// Example 2:
// Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
// Output: [1,3,5]
// Explanation: The function increases each value by the index it resides in.
// Example 3:
// Input: arr = [10,20,30], fn = function constant() { return 42; }
// Output: [42,42,42]
// Explanation: The function always returns 42.
// Constraints:
// 0 <= arr.length <= 1000
// -109 <= arr[i] <= 109
// fn returns a number
/**
* @param {number[]} arr
* @param {Function} fn
* @return {number[]}
*/
var map = function(arr, fn) {
let res = [];
for (let i = 0; i < arr.length; i++) {
res.push(fn(arr[i],i));
}
return res;
};
// use reduce
var map = function(arr, fn) {
const res=[]
arr.reduce((accum,curr,index)=>{
accum.push(fn(curr,index))
return accum
},res)
return res
};