I have an array of objects:
[{
id : 1,
tag: "video"
},
{
id : 2,
tag: "music"
},
{
id : 3,
tag: "video"
},
{
id : 4,
tag: "music"
},
{
id : 5,
tag: "video"
}]
I want to sort this array based on 2 factors:
- The initial position of the element
- The tag
Basically I should group the tags together but in the same time keep the order of the items added, the output should look like this:
[{
id : 1,
tag: "video"
},
{
id : 3,
tag: "video"
},
{
id : 5,
tag: "video"
},
{
id : 2,
tag: "music"
},
{
id : 4,
tag: "music"
}]
As you can see, now they are grouped by tag name but the initial order is kept. The item with id=1 is before the item with id=2 because it was added first, and so on.
Note that I can't use the id field for this sort since the real id is not an integer, it's a unique string which can not be compared. So instead of the id I should use the original position index.
My only solution which does not looks very good is to make a big block of code to make a for on the initial array and create a new array with the items placed in the perfect positions by checking the last item with the same tag that was added in the original array and grab it's position and add it into the new array on that position.
Any optimal solution for this? Thanks