I have a Javascript array of object. Each of them has an integer property type
in a range between 1 and 4. Depending on the client, I want to sort the array members by an individual number sequence of this type
property. My idea was to define an array with the desired sequence, for example const desiredOrder = [4, 2, 3, 1];
. Then my script should sort the array of objects by this list, while keeping the overall order. For example:
var list = [
{id: 1, type: 2},
{id: 2, type: 4},
{id: 3, type: 2},
{id: 4, type: 1},
{id: 5, type: 2},
{id; 6, type: 3}
];
var orderedList = [
{id: 2, type: 4},
{id: 1, type: 2},
{id: 3, type: 2},
{id: 5, type: 2},
{id; 6, type: 3},
{id: 4, type: 1}
];
In my real code, there is no actual id! I've just added that to make clear, that the order should not be changed.
How can I achieve that?
Edit:
Thank you for all your ideas. I've created a JSPerf with all four solutions. It looks like the version with the two nested for loops is the fastest by far. You can test it for yourself: