Skip to content

Commit 3f8a67d

Browse files
authored
Merge pull request #24 from giordanna/master
Add Array.prototype.flatMap() implementation
2 parents db155f8 + 8480d39 commit 3f8a67d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

implementations/flatMap.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
*
3+
MDN Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
4+
5+
The flatMap() method first maps each element using a mapping function,
6+
then flattens the result into a new array.
7+
The flat function is of depth 1.
8+
9+
The callback function is invoked with three arguments:
10+
- currentValue: current element being processed in the array
11+
- index: index of the current element being processed
12+
- array: array object that was called upon
13+
14+
thisArg is a value to use as 'this' when executing callback function
15+
16+
Example 1:
17+
[1, 2, 3, 4].flatMap(x => [x, x * 2]);
18+
must return:
19+
[1, 2, 2, 4, 3, 6, 4, 8]
20+
21+
Example 2:
22+
["it's Sunny in", "", "California"].flatMap(x => x.split(" "));
23+
must return:
24+
["it's","Sunny","in", "", "California"]
25+
*/
26+
27+
Array.prototype.flatMap = function myFlatMap(callback, thisArg) {
28+
const returnValue = [];
29+
30+
for (let i = 0; i < this.length; i += 1) {
31+
const element = callback.call(thisArg, this[i], i, this);
32+
33+
if (Object.prototype.toString.call(element) === '[object Array]') {
34+
for (let j = 0; j < element.length; j += 1) {
35+
returnValue.push(element[j]);
36+
}
37+
} else {
38+
returnValue.push(element);
39+
}
40+
}
41+
return returnValue;
42+
};

0 commit comments

Comments
 (0)