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

如何在JavaScript中按两列值对二维数组进行快速排序

JavaScript二维数组按两列数值排序实现方案

你需要的排序规则为:先按子数组第一个元素升序排列,第一个元素相等时按第二个元素升序排列,以下是两种实现方案:

方案1:使用内置Array.sort方法(推荐)

现代JS引擎对内置sort方法做了高度优化,绝大多数场景下性能足够,代码更简洁:

const arr = [
  [12, 3],
  [12, 2],
  [54, 43],
  [32, 12]
];

arr.sort((a, b) => {
  // 优先比较第一列
  if (a[0] !== b[0]) {
    return a[0] - b[0];
  }
  // 第一列相等时比较第二列
  return a[1] - b[1];
});

console.log(arr);
// 输出结果:[[12, 2], [12, 3], [32, 12], [54, 43]]

方案2:自定义快速排序实现

如果需要手动实现快速排序逻辑,可以参考如下代码,核心比较规则和上面保持一致:

// 快排主函数
function quickSort(arr, left = 0, right = arr.length - 1) {
  if (left < right) {
    const pivotPos = partition(arr, left, right);
    quickSort(arr, left, pivotPos - 1);
    quickSort(arr, pivotPos + 1, right);
  }
  return arr;
}

// 分区逻辑
function partition(arr, left, right) {
  const pivot = arr[right];
  let swapIndex = left - 1;
  for (let i = left; i < right; i++) {
    let compareRes = arr[i][0] - pivot[0];
    if (compareRes === 0) {
      compareRes = arr[i][1] - pivot[1];
    }
    // 当前元素比基准值小,交换位置
    if (compareRes < 0) {
      swapIndex++;
      [arr[swapIndex], arr[i]] = [arr[i], arr[swapIndex]];
    }
  }
  [arr[swapIndex + 1], arr[right]] = [arr[right], arr[swapIndex + 1]];
  return swapIndex + 1;
}

// 调用示例
const arr = [
  [12, 3],
  [12, 2],
  [54, 43],
  [32, 12]
];
quickSort(arr);
console.log(arr);
// 输出结果:[[12, 2], [12, 3], [32, 12], [54, 43]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:45:05