I am trying to sort array of objects with name.
Working Snippet:
const data = [
{
"title":"Smart S",
"tariff_id":"1301"
},
{
"title":"Smart M",
"tariff_id":"1306"
},
{
"title":"Smart L",
"tariff_id":"1303"
},
{
"title":"Start",
"tariff_id":"1304"
},
{
"title":"Smart 6",
"tariff_id":"1305"
},
{
"title":"Ausland",
"tariff_id":"888888",
},
{
"title":"Länderzone",
"tariff_id":"999999",
}
];
//Filtering the data by removing the unwanted data
const newTariffs = (data || []).filter((tariff) =>
tariff?.tariff_id != 888888 && tariff?.tariff_id != 999999
);
// Need to sort in this order
const tariffOrder = ["Start", "Smart S", "Smart M", "Smart L", "Smart 6"];
//Sort code that have been tried
const sortedTariffs = (newTariffs || []).sort((a, b) =>
tariffOrder.indexOf(a.title) > tariffOrder.indexOf(b.title) ? 1 : -1
);
console.log("sortedTariffs ", sortedTariffs);
From the above data, the requirement is that,
-> Need to remove two items with highest id ie.., 888888 and 999999 (Used filter method)
-> Then need to sort the new filtered array based on the tariff order,
"Start", "Smart S", "Smart M", "Smart L", "Smart 6"
Current Result:
[{"title":"Smart 6","tariff_id":"1305"},{"title":"Start","tariff_id":"1304"},{"title":"Smart S","tariff_id":"1301"},{"title":"Smart M","tariff_id":"1306"},{"title":"Smart L","tariff_id":"1303"}]
Expected Result:
[{"title":"Start","tariff_id":"1304"},{"title":"Smart S","tariff_id":"1301"},{"title":"Smart M","tariff_id":"1306"},{"title":"Smart L","tariff_id":"1303"}, {"title":"Smart 6","tariff_id":"1305"}]