I have an array of objects that also contain IDs like so:
const arr = [
{ id: "5ffca1c771138d181c3bde0b", otherValue: 10 },
{ id: "5ffca1c771138d181c3bde0e", otherValue: 3},
{ id: "5ffca1c771138d181c3bde12", otherValue: 7},
{ id: "5ffca1c771138d181c3bde04" otherValue: 1},
{ id: "5ffca1c771138d181c3bde08", otherValue: 11}
]
I then have second array, that contains a subset of the IDs of the first array in a particular ordering, like so:
const arrIds = [ "5ffca1c771138d181c3bde12", "5ffca1c771138d181c3bde08"];
I now want to sort the first array, so that the ordering is the same as in the second array, meaning the ordered subset is first, and the rest follows after, so that I get something like this:
[
{ id: "5ffca1c771138d181c3bde12", otherValue: 7}, // 1st place in subset
{ id: "5ffca1c771138d181c3bde08", otherValue: 11} // 2nd place in subset
{ id: "5ffca1c771138d181c3bde0b", otherValue: 10 }, // rest
{ id: "5ffca1c771138d181c3bde0e", otherValue: 3, // rest
{ id: "5ffca1c771138d181c3bde04" otherValue: 1}, // rest
]
How does the sorting function for this look like?
Current implementation:
arr.slice().sort((a, b) => arrIds.indexOf(a) - arrIds.indexOf(b))
which results in:
{ id: "5ffca1c771138d181c3bde0b", otherValue: 10 },
{ id: "5ffca1c771138d181c3bde0e", otherValue: 3,
{ id: "5ffca1c771138d181c3bde04" otherValue: 1},
{ id: "5ffca1c771138d181c3bde12", otherValue: 7},
{ id: "5ffca1c771138d181c3bde08", otherValue: 11},