【发布时间】:2021-11-03 08:55:21
【问题描述】:
我正在尝试使用名称对对象数组进行排序。
工作片段:
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);
从以上数据来看,要求是,
-> 需要删除 id 最高的两个项目,即 888888 和 999999(使用过滤方法)
-> 然后需要根据关税顺序对新过滤的数组进行排序,
"Start", "Smart S", "Smart M", "Smart L", "Smart 6"
当前结果:
[{"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"}]
预期结果:
[{"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"}]
【问题讨论】:
标签: javascript arrays sorting filter