Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: order array by taking alternately an object of each type

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 }
]
like image 699
flygge Avatar asked Oct 30 '22 01:10

flygge


1 Answers

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; }
like image 192
Nina Scholz Avatar answered Dec 22 '22 01:12

Nina Scholz