【问题标题】:Sort array of object based on another string array基于另一个字符串数组对对象数组进行排序
【发布时间】:2021-03-08 22:23:18
【问题描述】:

我有 2 个数组

a = [
     { label:"Price", value:10 }, 
     { label:"Active", value:false },
     { label:"Category", value:"food" },
     { label:"Remarks", value:"none" }
    ];

b = ["Active","Category","Price"];

如何根据 b 的顺序对 a 进行排序?我可以使用 ramda 吗?

像下面这样简洁的东西是理想的

R.sortBy(R.pipe(R.prop('label'), R.indexOf(R.__, a)))(b);

与这个问题类似,只是我没有索引,所以我不能使用 indexOf 方法。
Sort an array of objects based on another array of ids

感谢您的帮助!

【问题讨论】:

    标签: javascript angular typescript sorting


    【解决方案1】:

    可能有更简洁的选择,但我会这样做。

    const list = [
      {label:"Price", value:10},
      {label:"Active", value:false},
      {label:"Category", value:"food"},
      {label:"Remarks", value:"none"}
    ];
    const labels = ["Active","Category","Price"];
    
    const sorted = list.sort((a, b) => {
      const aIndex = labels.indexOf(a.label);
      const bIndex = labels.indexOf(b.label);
      return aIndex - bIndex;
    });
    
    console.log(sorted);

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      相关资源
      最近更新 更多