以下数组怎么按名称排序

{transferTotal: 4463838, touchTotal: 4463861, channelName: "其他", channelId: "OTHER"}

 {transferTotal: 10867488, touchTotal: 11260458, channelName: "支付宝", channelId: "ALIPAY"}

 {transferTotal: 1036820, touchTotal: 1094788, channelName: "微信", channelId: "WECHAT"}

需要按微信,支付宝,其他 来排序
我的办法很笨,就是遍历,如果是微信,push到新的数组里,把原数组的这个删了,在判断是支付宝,再删,有没有好办法

阅读 3.6k
2 个回答

预设个排序数组,map一遍就是你需要的结果了

let list = [
  {transferTotal: 4463838, touchTotal: 4463861, channelName: "其他", channelId: "OTHER"},
  {transferTotal: 10867488, touchTotal: 11260458, channelName: "支付宝", channelId: "ALIPAY"},
  {transferTotal: 1036820, touchTotal: 1094788, channelName: "微信", channelId: "WECHAT"}
];

let result = ['微信', '支付宝', '其他'].map(name => list.find(item => item.channelName === name));

console.log(result)

排序

var order = {
  微信: 0,
  支付宝: 1,
  其他: 2,
}
var orderArr = arr.sort(
  (a, b) =>
    order[a.channelName] - order[b.channelName]
)

分类

var classifyArr = arr.reduce(
  (prev, cur) => {
    prev[cur.channelName].push(cur)
    return prev
  },
  {
    微信: [],
    支付宝: [],
    其他: [],
  }
)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏