Despite my extensive search efforts, I have not been able to find a solution that meets my exact requirements. My question is: How can I sort an array based on the predefined order of another array?
For example-
const array1 = [
{
name: "1"
},
{
name: "2"
},
{
name: "3"
}
]
const array2 = ["3", "1"]
I need to rearrange array1 according to this custom order:
const array = [
{
name: "3"
},
{
name: "1"
},
{
name: "2"
}
]
In this case, the values from array2 should appear at the beginning of array1. I am seeking assistance in achieving this functionality.
Although I have made multiple attempts, the results have not been as expected-
const sortMarkets = (array: ArrayTypes[], sortArray: string[]) => {
return [...array].sort(
(a, b) => sortArray.indexOf(a.name) - sortArray.indexOf(b.name)
)
}
console.log(sortMarkets(array, ag));
The output I received was-
[{
"name": "2"
}, {
"name": "1"
}, {
"name": "3"
}]
Your help would be greatly appreciated.