按照两个键值对数组对象排序,同时将“其他”值推到第一个键的部分的末尾。
创始人
2024-08-24 13:00:38
0
const data = [
  { name: "John", age: 25, type: "other" },
  { name: "Jane", age: 30, type: "other" },
  { name: "Bob", age: 20, type: "a" },
  { name: "Sue", age: 35, type: "b" },
  { name: "Tom", age: 25, type: "a" },
  { name: "Tim", age: 30, type: "b" },
  { name: "Ann", age: 20, type: "a" },
  { name: "Jim", age: 35, type: "b" },
]

function sortData(arr, sortKey1, sortKey2, otherValue) {
  const sortedArray = arr.sort((a, b) => {
    if (a[sortKey1] < b[sortKey1]) return -1
    if (a[sortKey1] > b[sortKey1]) return 1
    if (a[sortKey2] < b[sortKey2]) return -1
    if (a[sortKey2] > b[sortKey2]) return 1
    return 0
  })

  const otherIndex = sortedArray.findIndex((item) => item[sortKey1] === otherValue)
  if (otherIndex >= 0) {
    const otherItem = sortedArray.splice(otherIndex, 1)
    sortedArray.push(...otherItem)
  }

  return sortedArray
}

const sortedData = sortData(data, "type", "age", "other")
console.log(sortedData)

以上示例中,我们定义了 sortData 函数,以及测试数据 data。函数取三个参数:原始数组、第一个排序键、第二个排序键和带“其他”值的字符串。 函数中使用 JavaScript 的 sort 函数对原始数组进行排序,按照第一个和第二个键进行比较。最终找到带“其他”值的对象,并将其从排序后的数组中取出并添加到末尾。 最后,我们将排序后的结果保存在 sortedData 变量中并输出。

相关内容

热门资讯

玩家必看(微扑克线上)外挂透明... 【福星临门,好运相随】;玩家必看(微扑克线上)外挂透明挂辅助器安装(透视)德州ai机器人(确实有挂)...
玩家必备科普!epoker外挂... 玩家必备科普!epoker外挂(辅助挂)透视辅助(有挂详情)-哔哩哔哩;人气非常高,ai更新快且高清...
科普常识(Wepoke教程)外... 科普常识(Wepoke教程)外挂透明挂辅助工具(辅助挂)透视辅助(2025已更新)(哔哩哔哩)1、每...
一分钟揭秘(德扑之星电脑)外挂... 1、一分钟揭秘(德扑之星电脑)外挂透明挂辅助器(透视)原来真的有挂(系统教程)(哔哩哔哩);详细教程...
科技分享(德州Wepoke)外... 科技分享(德州Wepoke)外挂透明挂辅助软件(辅助挂)发牌机制(有挂教程)-哔哩哔哩关于德州Wep...
一分钟教会你!德扑之星比赛创建... 1、一分钟教会你!德扑之星比赛创建设置(透视)辅助透视(有挂总结)-哔哩哔哩;详细教程。2、德扑之星...
必备攻略(微扑克代码)外挂透明... 必备攻略(微扑克代码)外挂透明挂辅助脚本(透视)透视辅助(2025已更新)(哔哩哔哩);《WPK辅助...
科普常识!红龙扑克有外挂(透视... 这是一款非常优秀的红龙扑克有外挂 ia辅助检测软件,能够让你了解到红龙扑克有外挂中牌率当中全部隐藏参...
分享实测(云扑克cloudpo... 分享实测(云扑克cloudpoker)外挂透明挂辅助挂(透视)的确真的有挂(玩家教你)(哔哩哔哩)准...
一分钟了解(德州版wpk)外挂... 此外,数据分析德州(德州版wpk)辅助神器app还具备辅助透视行为开挂功能,通过对客户德州版wpk透...