使用数组方法' .reduce() ',请编写逻辑来循环遍历对象数组并返回分析结果



我正在学习JavaScript reduce方法。

我需要帮助解决下面的问题

使用数组方法.reduce(),请编写遍历对象数组并返回分析的逻辑:

const orders = [
{  doctorId: 996, amount: 30500.35, tax: 0.06, isDisputed: true, isShipped: true },
{  doctorId: 910, amount: 100, tax: 0.08, isDisputed: true },
{  doctorId: 912, amount: 4200.11, tax: 0.06 },
{  doctorId: 996, amount: 99.12, tax: 0.06, isDisputed: false },
{  doctorId: 910, amount: 0.00, tax: 0.08, isShipped: true },
{  doctorId: 996, amount: 10, tax: 0.06, isDisputed: true },
];
// Expected result to be an object and have keys:
// - Total number of orders
// - Total disputed orders
// - Total disputed amount (included tax)
// - Total amount (included tax)
// - Total unique users
// - Total average sales per unique user
const result = collections.reduce(...);
console.log(result);

我试过了

const totalDisputedOrders = orders.reduce((acc, { isDisputed }) => isDisputed === true ? acc += 1 : acc, 0);

但是对如何在reduce

中声明初始结果对象感到困惑

虽然我不会为你完成这个练习,但这里有一个提示,告诉你如何开始。

const orders = [
{
doctorId: 996,
amount: 30500.35,
tax: 0.06,
isDisputed: true,
isShipped: true,
},
{ doctorId: 910, amount: 100, tax: 0.08, isDisputed: true },
{ doctorId: 912, amount: 4200.11, tax: 0.06 },
{ doctorId: 996, amount: 99.12, tax: 0.06, isDisputed: false },
{ doctorId: 910, amount: 0.0, tax: 0.08, isShipped: true },
{ doctorId: 996, amount: 10, tax: 0.06, isDisputed: true },
];
// Expected result to be an object and have keys:
// - Total number of orders
// - Total disputed orders
// - Total disputed amount (included tax)
// - Total amount (included tax)
// - Total unique users
// - Total average sales per unique user
const result = orders.reduce(
(result, item) => {
// here you have access to the previous computed metrics thus far (using result) and the curent order (using item)
// here's how you would do the first one, as an example
const numberOfOrders = result.numberOfOrders + 1;
// ... compute the rest of the metrics here ...
return {
numberOfOrders,
// ... return the rest of the results here ...
};
},
{
numberOfOrders: 0,
disputedOrders: 0,
disputedAmount: 0,
totalAmount: 0,
uniqueUsers: 0,
averageSalesPerUser: 0,
},
);
console.log(result);

如果你不明白发生了什么,首先阅读Array.prototype.reduce()文档。

祝你好运