Skip to content

Instantly share code, notes, and snippets.

@mitchallen
Last active December 24, 2018 13:25
Show Gist options
  • Save mitchallen/2e288a5168850da357d5982df5445f98 to your computer and use it in GitHub Desktop.
Save mitchallen/2e288a5168850da357d5982df5445f98 to your computer and use it in GitHub Desktop.
An example of using reduce in JavaScript to combine child arrays
/*
* 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