猿问

连接二维数组中具有相似值的元素

所以我的数组如下:


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。我正在尝试找到执行此操作的最佳算法,但找不到。


慕妹3146593
浏览 110回答 1
1回答

MMMHUHU

您可以使用组合钥匙并增加价值和数量。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; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答