Created
November 7, 2019 13:24
-
-
Save marekdano/b55bbd9c2b375d2b1a244b85ee37cf13 to your computer and use it in GitHub Desktop.
Create map, filter and reduce array functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // MAP | |
| function map(array, callbackFunction) { | |
| var newArray = []; | |
| for (var i = 0; i < array.length; i++) { | |
| newArray[i] = callbackFunction(array[i]); | |
| } | |
| return newArray; | |
| } | |
| // Test | |
| var input = [1, 2, 3, 4]; | |
| var output = map(input, function(value) { | |
| return value + 1; | |
| }) | |
| // FILTER | |
| function filter(array, callbackFunction) { | |
| var newArray = []; | |
| for (var i = 0; i < array.length; i++) { | |
| if (callbackFunction(array[i])) { | |
| newArray.push(array[i]) | |
| } | |
| } | |
| return newArray; | |
| } | |
| // Test | |
| var input = [1, 2, 3, 4]; | |
| var output = filter(input, function(value) { | |
| return value % 2 === 0; | |
| }) | |
| // REDUCE | |
| function reduce(array, callbackFunction, startingValue) { | |
| var result = startingValue | |
| for (var i = 0; i < array.length; i++) { | |
| result = callbackFunction(result, array[i]); | |
| } | |
| return result; | |
| } | |
| // Test | |
| var input = [1, 2, 3, 4]; | |
| var output = reduce(input, function(sum, value) { | |
| return sum + value; | |
| }, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment