Skip to content

Commit 47b7eb3

Browse files
committed
arrayelement
1 parent f2639fc commit 47b7eb3

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Programs/Exercise/arrayele.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2+
/*
3+
4+
Apply Transform Over Each Element in Array
5+
-----------------------------------------------------
6+
Given an integer array arr and a mapping function fn,
7+
return a new array with a transformation applied to each element.
8+
9+
The returned array should be created such that
10+
returnedArray[i] = fn(arr[i], i).
11+
12+
Please solve it without the built-in Array.map method.
13+
14+
15+
16+
Example 1:
17+
18+
Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
19+
Output: [2,3,4]
20+
Explanation:
21+
const newArray = map(arr, plusone); // [2,3,4]
22+
The function increases each value in the array by one.
23+
*/
24+
25+
var map = function(arr, fn) {
26+
const result = [];
27+
28+
for (let i = 0; i < arr.length; i++) {
29+
result.push(fn(arr[i], i));
30+
}
31+
32+
return result;
33+
};
34+
35+
function plusOne(n) {
36+
return n + 1;
37+
}
38+
39+
console.log(map([1,2,3], plusOne)); // [2,3,4]

0 commit comments

Comments
 (0)