Last active
December 24, 2018 13:25
-
-
Save mitchallen/2e288a5168850da357d5982df5445f98 to your computer and use it in GitHub Desktop.
An example of using reduce in JavaScript to combine child arrays
This file contains 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
/* | |
* An example of using reduce to combine child arrays | |
* | |
* Expected Output: | |
SOURCE: | |
[ | |
{ | |
"name": "alpha", | |
"kids": [ | |
"beta", | |
"gamma" | |
] | |
}, | |
{ | |
"name": "delta", | |
"kids": [ | |
"epsilon", | |
"hydra" | |
] | |
} | |
] | |
TARGET: | |
[ | |
"beta", | |
"gamma", | |
"epsilon", | |
"hydra" | |
] | |
*/ | |
const source = [ | |
{ name: 'alpha', kids: ['beta','gamma']}, | |
{ name: 'delta', kids: ['epsilon','hydra']} | |
]; | |
console.log(`SOURCE:\n ${JSON.stringify(source,null,2)}`); | |
/* | |
* You must end reduce with '[]' to tell JS that prev is an array | |
* or you will get 'concat is not a function' (more like method of prev is not a function) | |
*/ | |
const target = source.reduce( (prev, curr) => prev.concat(curr.kids), [] ); | |
console.log(`TARGET:\n ${JSON.stringify(target,null,2)}`); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment