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

JavaScript:如何对生成全组合的二维数组进行数值排序?

Solution to Sort the Combination Results from getCombinations

First, let's recap: your existing getCombinations function generates all non-empty subsets of the input array (e.g., for [1,2,3,4], it returns everything from [1] up to [1,2,3,4]). To sort these subsets numerically, there are two common, practical sorting goals—let's break down both with working code implementations.

1. Sort by the Sum of the Combination (Ascending Order)

This orders subsets based on their total numerical value, with tiebreakers for length and element order if sums are equal. Here's how to implement it:

function getCombinations(_list) {
  var fn = function(active, rest, a) {
    if (!active.length && !rest.length) return;
    if (!rest.length) {
      a.push(active);
    } else {
      fn(active.concat(rest[0]), rest.slice(1), a);
      fn(active, rest.slice(1), a);
    }
    return a;
  }
  return fn([], _list, []);
}

// Helper to calculate the sum of a subset
const calculateSum = arr => arr.reduce((total, num) => total + num, 0);

// Generate combinations and sort by sum (with tiebreakers)
const inputList = [1, 2, 3, 4];
const sortedBySum = getCombinations(inputList).sort((subsetA, subsetB) => {
  const sumA = calculateSum(subsetA);
  const sumB = calculateSum(subsetB);

  // First priority: sort by sum (smallest first)
  if (sumA !== sumB) {
    return sumA - sumB;
  }
  // Tiebreaker 1: shorter subsets come first if sums are equal
  if (subsetA.length !== subsetB.length) {
    return subsetA.length - subsetB.length;
  }
  // Tiebreaker 2: sort elements numerically if sum and length match
  for (let i = 0; i < subsetA.length; i++) {
    if (subsetA[i] !== subsetB[i]) {
      return subsetA[i] - subsetB[i];
    }
  }
  return 0;
});

console.log(sortedBySum);

How it works:

  • The calculateSum helper quickly computes the total value of any subset.
  • The sort comparator first prioritizes sum, then falls back to length, then element order to ensure consistent results even for subsets with identical sums.

2. Sort by Combination Length, Then Element Order (Ascending)

This groups subsets by their size first (all 1-element subsets, then 2-element, etc.), and sorts subsets of the same size numerically. This is useful if you want to organize results by subset length:

// Reuse the existing getCombinations function here

const inputList = [1, 2, 3, 4];
const sortedByLengthThenElements = getCombinations(inputList).sort((subsetA, subsetB) => {
  // First priority: shorter subsets come first
  if (subsetA.length !== subsetB.length) {
    return subsetA.length - subsetB.length;
  }
  // Same length: sort elements one by one numerically
  for (let i = 0; i < subsetA.length; i++) {
    if (subsetA[i] !== subsetB[i]) {
      return subsetA[i] - subsetB[i];
    }
  }
  return 0;
});

console.log(sortedByLengthThenElements);

How it works:

  • The comparator first sorts by subset length, so all single-element subsets appear before pairs, which come before triples, etc.
  • For subsets of the same length, it iterates through elements to ensure numerical order (e.g., [1,2] comes before [1,3]).

Quick Adjustments

  • To sort in descending order, reverse the subtraction logic (e.g., sumB - sumA for sum-based descending sort, or subsetB.length - subsetA.length for length-based descending).
  • To include the empty array in results, remove the if (!active.length && !rest.length) return; line from the original getCombinations function—it will then be the first entry in both sorted lists.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:27:08