Created
September 9, 2017 01:20
-
-
Save ryan-hamblin/04f7e53958d6ca0203cfd011d8383763 to your computer and use it in GitHub Desktop.
reduce and flatten methods from ground up
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
| const nums = ['1', '2', '3', '4', '5']; | |
| const listOfPeeps = [ | |
| { | |
| _id: '123512', | |
| name: 'Ryan', | |
| friends: ['Hermione', 'Ron', 'Harry', 'Draco'], | |
| }, | |
| { | |
| name: 'Donnie', _id: '32434', | |
| friends: ['Batman', 'Superman', 'Thing', 'Human Torch', 'Cyborg'], | |
| } | |
| ] | |
| const customReduce = (arr, callBack, memo = arr.shift()) => { | |
| for (let i = 0; i < arr.length; i++) { | |
| memo = callBack(memo, arr[i]); | |
| } | |
| return memo; | |
| }; | |
| const sum = customReduce(listOfPeeps, (object, item) => { | |
| object[item._id] = item; | |
| return object; | |
| }, {}); | |
| console.log(sum); | |
| const flatten = (arr) => { | |
| let newArr = []; | |
| for ( let i = 0; i < arr.length; i++ ) { | |
| if (Array.isArray(arr[i])) { | |
| newArr = newArr.concat(flatten(arr[i])); | |
| } else { | |
| newArr.push(arr[i]); | |
| } | |
| } | |
| return newArr; | |
| }; | |
| const nestedArr = [1, 2, 3, [4], [[5], [6, [7], [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[3, [[[[[[[[[[[[[[[[[[[[[[[[[[[234]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]; | |
| console.log(flatten(nestedArr)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment