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

如何从对象数组中获取同属性的所有左到右索引组合

问题描述

给定如下格式的对象数组:

[{ property1: 10 }, { property1: 13 }, { property1: 15 }, { property2: 2 }]

需要编写一个函数,返回一个对象,其中包含所有同属性元素的左到右索引组合(即索引对中前者小于后者),示例输出:

{ property1: [[0, 1], [0, 2], [1, 2]] }

更多示例:

  • 输入:
[{ property1: 10 }, { property1: 13 }, { property2: 15 }, { property2: 2 }]

输出:

{
    property1: [[0, 1]],
    property2: [[2, 3]]
}
  • 输入(4个同属性元素):
[{ property1: 10 }, { property1: 13 }, { property1: 15 }, { property1: 2 }]

输出:

{
    property1: [[0, 1], [0,2], [0,3], [1,2], [1,3], [2,3]]
}

目前已能统计同属性元素数量或获取对应索引,但不知道如何生成这类左到右的索引组合。

解决方案

核心思路分两步:

  1. 收集同属性的索引列表:遍历输入数组,把每个元素的属性名作为键,对应的索引存入数组中。
  2. 生成所有左到右的索引组合:对每个属性的索引列表,生成所有i < j的索引对(即数学上的组合数C(n,2),n为该属性的元素个数)。

代码实现(JavaScript)

function generateIndexPairs(arr) {
    // 收集每个属性对应的索引列表
    const propertyIndices = {};
    arr.forEach((item, index) => {
        // 假设每个元素仅含一个属性(匹配示例格式)
        const prop = Object.keys(item)[0];
        propertyIndices[prop] ??= [];
        propertyIndices[prop].push(index);
    });

    // 生成左到右的索引对
    const result = {};
    for (const [prop, indices] of Object.entries(propertyIndices)) {
        const pairs = [];
        // 外层循环取基准索引,内层循环取基准之后的所有索引
        for (let i = 0; i < indices.length; i++) {
            for (let j = i + 1; j < indices.length; j++) {
                pairs.push([indices[i], indices[j]]);
            }
        }
        result[prop] = pairs;
    }
    return result;
}

关键说明

  • 收集索引时,默认每个数组元素仅含一个属性;若元素有多个属性,可修改为遍历元素的所有属性名,将索引对应存入每个属性的列表中。
  • 双重循环的逻辑确保所有索引对都是左到右顺序(前者索引小于后者),不会产生逆序对。
  • 对于n个同属性元素,最终会生成n*(n-1)/2个索引对,完全匹配示例中的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 07:47:47