首页 > 解决方案 > 连接具有相似值的二维数组中的元素

问题描述

所以我的数组如下:

array = [ [5, type1, quantity1, price1] , 
      [2, type2, quantity2, price2] ,
      [2, type1, quantity3, price1]
    ]

上述值不是恒定的,它们可以变化。重要的是它们匹配并且它们加在一起创建 1 个元素。

因此,由于array[0]array[2]具有相同的类型和价格 ( array[n][1] and array[n][3]),结果数组应如下所示:

[ [7, type1, quantity1+quantity3, price1], 
  [2, type2, quantity2, price2]
]

该数组的长度为 N。我正在尝试找到执行此操作的最佳算法,但找不到。

提前致谢。

标签: javascriptarrayssortingmultidimensional-array

解决方案


您可以使用组合键并添加价值和数量。

const
    array = [[5, 'type1', 10, 'price1'], [2, 'type2', 11, 'price2'], [2, 'type1', 12, 'price1']],
    grouped = Object.values(array.reduce((r, [value, type, quantity, price]) => {
        const key = [type, price].join('|');
        if (r[key]) {
            r[key][0] += value;
            r[key][2] += quantity;
        } else r[key] = [value, type, quantity, price];
        return r;
    }, {}));

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读