You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按type优先级对对象数组的嵌套answers子字段进行排序

实现方案

实现思路

  • 首先定义类型优先级映射,给每个type分配对应权重:video优先级最高权重设为1,audio次高权重设为2,text优先级最低权重设为3,排序时直接比较权重值大小即可
  • 遍历posts数组的每一项,对每一项的answers子数组调用JavaScript原生的sort()方法完成排序
  • 同类型元素排序后保持原有相对顺序,符合稳定排序要求

代码实现

如果可以直接修改原数组,可直接使用以下代码:

// 定义类型优先级映射,数值越小排序越靠前
const typePriority = {
  video: 1,
  audio: 2,
  text: 3
}

// 遍历所有post对answers排序
posts.forEach(post => {
  post.answers.sort((a, b) => {
    return typePriority[a.type] - typePriority[b.type]
  })
})

如果需要保留原数组不被修改,可以使用深拷贝后生成新数组的版本:

const typePriority = {
  video: 1,
  audio: 2,
  text: 3
}

const sortedPosts = posts.map(post => ({
  ...post,
  // 先拷贝answers数组再排序,避免修改原数组
  answers: [...post.answers].sort((a, b) => typePriority[a.type] - typePriority[b.type])
}))

执行上述代码后即可得到你要求的排序结果。

内容的提问来源于stack exchange,提问作者Rajat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 22:36:03