I have an array called "sortOrder" in which i expect to use as the model order i want to sort my "dataSet" array with.
const sortOrder = [
"FirstName",
"LastName",
"Address",
"City",
"State",
"Zip",
"Country" ]
const dataSet = [
{ Zip: "00199",
City: "Birmingham",
State: "AL",
LastName: "Ellis",
Country: "USA",
FirstName: "Dominique",
Address: "127 East Avenue J St",
},
{ Zip: "95421",
City: "San Francisco",
State: "CA",
LastName: "Orlando",
Country: "USA",
FirstName: "Mitchell",
Address: "90 Market Street Unit 2",
},
{ Zip: "DN11 5XQ",
City: "Wadworth",
State: "AL",
LastName: "Connolly",
Country: "UK",
FirstName: "John",
Address: "130 New Dover Rd",
}
]
Goal: To have something like the below object ordered based on keys found in the "sortOrder" array:
{ FirstName: "Dominique",
LastName: "Ellis",
Address: "127 East Avenue J St",
City: "Birmingham",
State: "AL",
Zip: "00199",
Country: "USA" }
I've tried to use sort method to handle the sort but its not working. Any advice on how to get this dataset sorted by the key?
My failed attempt:
dataSet.sort((a, b) => {
return sortOrder.indexOf(a) - sortOrder.indexOf(b);
});
console.log("SortedDataSet", dataSet);