有效使用Map,Reduce或filter来查找给定对象数组的信息

时间:2016-03-09 10:07:02

标签: javascript functional-programming list-comprehension

ordersList = [
  [{
      id: 1,
      name: "chicken Burger",
      sellPrice: 20,
      buyPrice: 15,
      qty: 5
    }, {
      id: 2,
      name: "Beef Burger",
      sellPrice: 22,
      buyPrice: 16,
      qty: 3
    }, {
      id: 3,
      name: "Chicken Sandwich",
      sellPrice: 15,
      buyPrice: 13,
      qty: 2
    }
  ],
  [{
      id: 1,
      name: "Beef Burger",
      sellPrice: 22,
      buyPrice: 16,
      qty: 2
    }, {
      id: 2,
      name: "Chicken Sandwich",
      sellPrice: 15,
      buyPrice: 13,
      qty: 2
    }
  ],
  [{
      id: 1,
      name: "Chicken Sandwich",
      sellPrice: 15,
      buyPrice: 13,
      qty: 20
    }, {
      id: 1,
      name: "Beef Burger",
      sellPrice: 15,
      buyPrice: 13,
      qty: 10
    }
  ]
]

应使用item-title(键)创建新对象,(总数量, 来自给定JSON DATA的Total BuyPrice和Total SellPrice)(值)。这个问题的目的是找出列表理解,不可变状态,功能样式如何用于查找下面给出的数据。

例如 - { 'chicken Burger': { totalQty: 5, buySumPrice: 75, sellSumPrice: 100 }, 'Beef Burger': { totalQty: 15, buySumPrice: 210, sellSumPrice: 260 }, 'Chicken Sandwich': { totalQty: 24, buySumPrice: 312, sellSumPrice: 360 } }

function getAll() {
  var total = {};
  ordersList.map(function(orders) {
    orders.map(function(order) {
      total[order.name] = total[order.name] ? ({
        qty: (total[order.name]).qty + order.qty,
        buySumPrice:(total[order.name]).buySumPrice + order.buyPrice*order.qty ,
        sellSumPrice: (total[order.name]).sellSumPrice + order.sellPrice*order.qty
      }) : ({
        qty: order.qty,
        buySumPrice: order.buyPrice*order.qty,
        sellSumPrice: order.sellPrice*order.qty
      });
    });
  });
  return total;
}

是否可以通过从地图返回构造的数组来移除外部总数{}。还使用reduce来进行求和计算。

1 个答案:

答案 0 :(得分:0)

这里有一个真正的问题。我将使用ES6解决它,因为它有一些工具可以使这种事情变得更容易。如果您需要ES5,请将其复制/粘贴到babel或向您的应用程序添加构建步骤。

const getData = ordersList => {
  let merge = ({totalQty=0, buySumPrice=0, sellSumPrice=0}={}, {qty, buyPrice, sellPrice}) => ({
    totalQty: totalQty + qty,
    buySumPrice: buySumPrice + (qty * buyPrice),
    sellSumPrice: sellSumPrice + (qty * sellPrice)
  });
  return ordersList.reduce((ys, xs) => {
    xs.forEach(x => Object.assign(ys, {[x.name]: merge(ys[x.name], x)}));
    return ys;
  }, {});
};

let answer = getData(ordersList);

console.log(JSON.stringify(answer, null, "\t"));

输出

{
    "chicken Burger": {
        "totalQty": 5,
        "buySumPrice": 75,
        "sellSumPrice": 100
    },
    "Beef Burger": {
        "totalQty": 15,
        "buySumPrice": 210,
        "sellSumPrice": 260
    },
    "Chicken Sandwich": {
        "totalQty": 24,
        "buySumPrice": 312,
        "sellSumPrice": 360
    }
}

<强>说明:

这个问题中最丑陋的部分是Arrays是嵌套的。如果您能够flatten Array(Array(Object{}))结构Array(Object{}),那么这将是一个更好的问题。但是,这需要两次遍历列表。对于相当大的输入,计算开销可能是一个交易破坏者。