There are a lot of questions like this on here, but I couldn't find one that matched my needs. I'm looking for a relatively simple solution on how to stack objects in an array into new arrays based on a key.
In the example data we're grouping the objects by their "ship" key.
Original data:
var myObjArray = [
{
name:'Malcolm Reynolds',
ship:'Serenity'
},
{
name: 'Carmen Ibanez',
ship: 'Rodger Young',
},
{
name: 'Zander Barcalow',
ship: 'Rodger Young',
},
{
name:'Hoban Washburne',
ship:'Serenity'
},
{
name:'James Kirk',
ship:'USS Enterprise'
}
];
Restructured Data:
var myNewObjArray = [
[{
name:'Malcolm Reynolds',
ship:'Serenity'
},
{
name:'Hoban Washburne',
ship:'Serenity'
}],
[{
name: 'Carmen Ibanez',
ship: 'Rodger Young',
},
{
name: 'Zander Barcalow',
ship: 'Rodger Young',
}],
{
name:'James Kirk', // optionally also stick in an array
ship:'USS Enterprise'
}
];
If anyone has a solution for this I'd appreciate it, my current attempt is sloppy to say the least.
.sort(customCompare)wherecustomCompare = function(a,b){.....}