I have an array of objects like this (ordered by type, the objects of the same type are identical):
[
{ "type":"A", "height":50, "width":80 },
{ "type":"A", "height":50, "width":80 },
{ "type":"B", "height":20, "width":100 },
{ "type":"B", "height":20, "width":100 },
{ "type":"C", "height":90, "width":10 }
]
I want to have all these objects in an array which is ordered by taking alternately an object of each type:
[
{ "type":"A", "height":50, "width":80 },
{ "type":"B", "height":20, "width":100 },
{ "type":"C", "height":90, "width":10 },
{ "type":"A", "height":50, "width":80 },
{ "type":"B", "height":20, "width":100 }
]
You could take a Map
and iterate until all items are processed in the right order.
var array = [{ type: "A", height: 50, width: 80 }, { type: "A", height: 50, width: 80 }, { type: "B", height: 20, width: 100 }, { type: "B", height: 20, width: 100 }, { type: "C", height: 90, width: 10 }],
order = ['A', 'B', 'C'],
types = new Map(order.map(k => [k, []])),
result = [];
array.forEach(o => types.get(o.type).push(o));
while (types.size) {
types.forEach((a, k) => (result.push(a.shift()), a.length || types.delete(k)));
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With