【问题标题】:How to sort array with name?如何按名称对数组进行排序?
【发布时间】: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 最高的两个项目,即 888888999999(使用过滤方法)

-> 然后需要根据关税顺序对新过滤的数组进行排序,

"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


    【解决方案1】:

    按标题排序:

    const sortedTariffs = (newTariffs || []).sort((a, b) =>
        a.title.localeCompare(b.title)
    );
    

    localeCompare 将比较两个字符串并返回 -1 或 1,正如 sort 所期望的那样。

    编辑:

    再次阅读问题后,我误读了ir。你遇到的问题是字符串“Smart 6”有2个空格而不是1个,所以indexOf()返回-1,它放在第一位

    【讨论】:

    • 以上结果为[{"title":"Smart 6","tariff_id":"1305"},{"title":"Smart L","tariff_id":"1303"},{"title":"Smart M","tariff_id":"1306"},{"title":"Smart S","tariff_id":"1301"},{"title":"Start","tariff_id":"1304"}]
    • @HelloWorld 对不起,我误读了这个问题。问题编辑:Smart 6 有 2 个空格,所以在 tariffOrder 中找不到它
    【解决方案2】:

    您需要像这样更改顺序以获得升序或排序。

    var sortedTariffs = newTariffs.sort((a, b) =>
        (a.title < b.title) - (a.title > b.title)
    );
    

    【讨论】:

    • 能否在不提供排序顺序数组的情况下详细解释一下这是如何工作的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2019-11-04
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多