I want to sort an array in a complicated way and am not sure how to go about it. Here is a rough idea of the data I'm working with:
[
{ target: random.text.cpu-pct-0, otherData[...] },
{ target: random.text.cpu-pct-1, otherData[...] },
{ target: random.text.cpu-pct-2, otherData[...] },
{ target: random.text.example-0, otherData[...] },
{ target: random.text.example-1, otherData[...] },
{ target: random.text.memory, otherData[...] },
...
]
I want all the objects with a target
that includes the string cpu-pct
to come first, then the objects with a target
that includes the string memory
, then example
. This array could have any number of items, so re-sorting by index won't work. There could be 1 object with a target
that includes cpu-pct
, or there could be 50+. Same goes for the other strings I'm sorting by.
I thought about looping over the original array, checking if the desired string exists, saving the matching objects to new arrays for each target I'm looking for, then merging the arrays at the end. I think that would work, but I'd imagine there is a better, more efficient solution, probably using usort
, but I'm at a loss. Any ideas?