I am searching any times, but I am not finding any solution exactly what I want. My question is How can I sort array with another array that defined the array order.
Suppose-
const array1 = [
{
name: "1"
},
{
name: "2"
},
{
name: "3"
}
]
const array2 = ["3", "1"]
I need to sort array1 by following
const array = [
{
name: "3"
},
{
name: "1"
},
{
name: "2"
}
]
Here, we can see array2 values are now top of array1. I want this function.
I already tried, but gives wrong result-
const sortMarkets = (array: ArrayTypes[], sortArray: string[]) => {
return [...array].sort(
(a, b) => sortArray.indexOf(a.name) - sortArray.indexOf(b.name)
)
}
console.log(sortMarkets(array, ag));
It gives me-
[{
"name": "2"
}, {
"name": "1"
}, {
"name": "3"
}]
Please help me.