-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDCC-17.js
29 lines (21 loc) · 1.07 KB
/
DCC-17.js
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
// Prompt:
// The goal is of this challenge is to write a function that performs the functionality of JavaScript's Array.prototype.map method.
// - Write a function named mapArray that accepts two arguments: a single array and a callback function.
// - The mapArray function should return a new array of the same length as the array argument.
// - The mapArray function should iterate over each element in the array (first arg). For each iteration, invoke the callback function (2nd arg), passing to it as arguments, the current element and its index. Whatever is returned by the callback function should be included in the new array at the index of the current iteration.
// Examples:
// mapArray( [1, 2, 3], function(n) {
// return n * 2;
// } );
// //=> [2, 4, 6] (a new array)
// mapArray( ['rose', 'tulip', 'daisy'], function(f, i) {
// return `${i + 1} - ${f}`;
// } );
// //=> ["1 - rose", "2 - tulip", "3 - daisy"]
const mapArray = (arr, callback) => {
const newArr = [];
for (let i = 0; i < arr.length; i++) {
newArr.push(callback(arr[i], i, arr));
}
return newArr;
};