Reputation: 3543
I have this array of objects and I want to organize the objects based on their units like this:
const array = [
{ unit: 5, id: 'five'},
{ unit: 200, id: 'some22'},
{ unit: 100, id: 'recall'},
{ unit: 5, id: 'some'},
];
// Result :
[
[ { unit: 5, id: 'five'}, { unit: 5, id: 'some'}, ],
[ { unit: 6, id: 'some22'} ],
[ { unit: 55, id: 'recall'} ],
]
Note: we can simply use filter method to get the array but in my case we don't know the units and we just want to order and organize them
Upvotes: 1
Views: 72
Reputation: 22360
You could use a Map:
const array = [
{ unit: 5, id: 'five'},
{ unit: 200, id: 'some22'},
{ unit: 100, id: 'recall'},
{ unit: 5, id: 'some'},
];
const unitGroups = new Map();
for (const obj of array) {
if (!unitGroups.has(obj.unit)) {
unitGroups.set(obj.unit, []);
}
unitGroups.get(obj.unit).push(obj);
}
const result = Array.from(unitGroups.values());
console.log(result);
Upvotes: 1
Reputation: 14730
A different approach using the build in array method reduce
, just to create a one-liner. Details to the under appreciated reduce
function Array.prototype.reduce
// Initial Data
const array = [
{ unit: 5, id: 'five'},
{ unit: 200, id: 'some22'},
{ unit: 100, id: 'recall'},
{ unit: 5, id: 'some'},
];
let result = array.reduce (function(last, next){
// find index of a List with matching unit
let index = last.findIndex((itemList) => itemList.some( item => item.unit == next.unit));
if(index == -1){ // if no match was found
index = last.push([]) - 1; // add an empty Array and set the index
}
last[index].push(next); // add the Entry to the selected List
return last;
}, [])
console.info(result);
btw.: I'm asuming the posted result data is incorrect, since the "units" for some22 and recall don't match with the initial data. If this assumption is wrong please clarify
Extra: just for kicks and giggles the whole thing as a real one-liner:
( Don't try this at home ;-) )
const array = [
{ unit: 5, id: 'five'},
{ unit: 200, id: 'some22'},
{ unit: 100, id: 'recall'},
{ unit: 5, id: 'some'},
];
console.info( array.reduce((p, c) => ((p.find( l => l.some(i => i.unit == c.unit)) || p[p.push([]) - 1]).push(c), p), []));
Upvotes: 1