My request to the API returns an array of objects. I need to group each item in this array based on the value of one of its keys. Thus, I need to end up with a 2d array of arrays.
Last active
February 10, 2017 11:52
-
-
Save kyleshevlin/d827b563e449aa8992e27a0592a35156 to your computer and use it in GitHub Desktop.
Help me create a better 2d array, please
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
// API returns an array | |
const array = [ | |
{ foreign_key: 1 }, | |
{ foreign_key: 2 }, | |
{ foreign_key: 1 }, | |
{ foreign_key: 1 }, | |
{ foreign_key: 3 }, | |
{ foreign_key: 2 }, | |
{ foreign_key: 3 }, | |
{ foreign_key: 1 }, | |
{ foreign_key: 2 }, | |
{ foreign_key: 3 }, | |
{ foreign_key: 3 }, | |
{ foreign_key: 1 } | |
] | |
// Reduce to an object with keys of the foreign_key | |
const groupByForeignKeys = items.reduce((acc, cur) => { | |
if (!acc[cur.foreign_key]) { | |
acc[cur.foreign_key] = [] | |
} | |
acc[cur.foreign_key].push(cur) | |
return acc | |
}, {}) | |
// Create our empty 2d array | |
let twoDArray = [] | |
// For each key, push the value of arrays to our now 2d array | |
for (let key in groupByForeignKeys) { | |
twoDArray.push(groupByForeignKeys[key]) | |
} | |
// This is what I'm getting and expecting | |
// twoDArray === [ | |
// [ { foreign_key: 1 }, { foreign_key: 1 }, { foreign_key: 1 }, { foreign_key: 1 } ], | |
// [ { foreign_key: 2 }, { foreign_key: 2 }, { foreign_key: 2 } ], | |
// [ { foreign_key: 3 }, { foreign_key: 3 }, { foreign_key: 3 }, { foreign_key: 3 } ] | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So I think the overall solutions would look like this...