javascript 如何使用ES6 reduce对另一个属性的值求和

9udxz4iz  于 2023-04-19  发布在  Java
关注(0)|答案(2)|浏览(137)

我有一个这样的数组:

const products = 
[{product: "a", volume: 3}, {product: "b", volume: 7}, {product: "c", volume: 5}],

[{product: "a", volume: 8}, {product: "b", volume: 10}, {product: "c", volume: 4}]

我需要对它们求和,并确保每个产品的体积不会比另一个具有相同结构的物体的体积大:

const ProductLimits: ProductVolumes[] = [{product: "a", volume: 10}, {product: "b", volume: 22}, {product: "c", volume: 12}]

已使用

products.flatMap(x => x.map(y => {
return { product: y.product, volume: y.volume }}));

其将阵列的第一阵列展平为单个阵列:

[{product: "a", volume: 3}, {product: "b", volume: 7}, {product: "c", volume: 5},
{product: "a", volume: 8}, {product: "b", volume: 10}, {product: "c", volume: 4}]

然后为了求和我在做

.reduce(acc: IInterface, i) => {
   acc[i.product] = acc[i.product] || 0) + i.volume;
   return acc;
});

使用

interface IInterface {
product: string;
volume: number;
[product: string]: any;
}

因为Typescript需要索引签名。
然而,问题是reduce返回了一个正确的产品列表,除了第一个产品,在3次迭代后,它有:

product: "a"
volume: 3
b: 7
c: 5

这个问题显然与acc的第一个值的结构有关。
关于如何修复第一次迭代或更好的方法,有什么想法吗?

xvw2m8pv

xvw2m8pv1#

你可以使用flat()来扁平化数组。然后你需要将reduce()种子/初始化为一个空对象{},然后聚合应该工作(你需要修复丢失的括号!)。最后但并非最不重要的是,你只需要使用Object.entries()将聚合值Map到所需的目标结构中。
注意,我也使用了nullish coalescing assignment,因为我认为这比使用falsy值更具可读性。

const input = [
  [{
    product: "a",
    volume: 3
  }, {
    product: "b",
    volume: 7
  }, {
    product: "c",
    volume: 5
  }],
  [{
    product: "a",
    volume: 8
  }, {
    product: "b",
    volume: 10
  }, {
    product: "c",
    volume: 4
  }]
];
const aggregated = input.flat()
  .reduce((acc, i) => {
    acc[i.product] = (acc[i.product] ??= 0) + i.volume;
    return acc;
  }, {});

const output = Object.entries(aggregated).map(([product, volume]) => ({ product, volume }));

console.log(output)
bhmjp9jg

bhmjp9jg2#

let products = [[{product: "a", volume: 3}, {product: "b", volume: 7}, {product: "c", volume: 5}], [{product: "a", volume: 8}, {product: "b", volume: 10}, {product: "c", volume: 4}]]

let SingleArray =  products.flat()
function Customfun(){
    let map = new Map();
    let type = "";
    for(let obj of SingleArray){
        if(map.has(obj.product)){
           let vol = map.get(obj.product)
           map.set(obj.product,obj.volume+vol);
        }
        else{
            map.set(obj.product,obj.volume);
        }
    }

    let ProductsList = [];
    for(let [key,val] of map.entries()){
        ProductsList = [...ProductsList,{product:key, volume:val}]
    }
    
    return ProductsList;
}
console.log(Customfun())

相关问题