gpt4 book ai didi

javascript - 困扰为什么 split 功能不起作用

转载 作者:行者123 更新时间:2023-11-28 05:21:20 25 4
gpt4 key购买 nike

我正在尝试拆分 salesData,它确实希望通过每个对象后面的逗号来 split()

这是作业。我试图将其存储在对象映射中并在那里进行计算。现在我无法克服让我失望的 split 函数。

我在下面提供了我的代码,以显示最终结果最赚钱的部门是什么。

var salesData = [
{department : 'hardware', sales : 4500, day : 'Monday'},
{department : 'outdoor', sales : 1500, day : 'Monday'},
{department : 'carpentry', sales : 5500, day : 'Monday'},
{department : 'hardware', sales : 7500, day : 'Tuesday'},
{department : 'outdoor', sales : 2505, day : 'Tuesday'},
{department : 'carpentry', sales : 1540, day : 'Tuesday'},
{department : 'hardware', sales : 1500, day : 'Wednesday'},
{department : 'outdoor', sales : 8507, day : 'Wednesday'},
{department : 'carpentry', sales : 8009, day : 'Wednesday'},
{department : 'hardware', sales : 12000, day : 'Thursday'},
{department : 'outdoor', sales : 18007, day : 'Thursday'},
{department : 'carpentry', sales : 6109, day : 'Thursday'},
{department : 'hardware', sales : 7005, day : 'Friday'},
{department : 'outdoor', sales : 12006, day : 'Friday'},
{department : 'carpentry', sales : 16109, day : 'Friday'},
];

var departmentMap = {};

function mostProfitableDepartment() {
var departmentSplit = salesData.split(',');

for (var i = 0; i < departmentSplit.length; i++) {
var currentDep = departmentSplit[i]
if (departmentMap[currentDep] === undefined) {
departmentMap[currentDep] = 0;
}
departmentMap[currentDep] = departmentMap[currentDep]++
}
console.log(departmentMap);
}mostProfitableDepartment(salesData);

最佳答案

您可以使用Array.prototype.reduce()进行如下操作

var salesData = [
{department : 'hardware', sales : 4500, day : 'Monday'},
{department : 'outdoor', sales : 1500, day : 'Monday'},
{department : 'carpentry', sales : 5500, day : 'Monday'},
{department : 'hardware', sales : 7500, day : 'Tuesday'},
{department : 'outdoor', sales : 2505, day : 'Tuesday'},
{department : 'carpentry', sales : 1540, day : 'Tuesday'},
{department : 'hardware', sales : 1500, day : 'Wednesday'},
{department : 'outdoor', sales : 8507, day : 'Wednesday'},
{department : 'carpentry', sales : 8009, day : 'Wednesday'},
{department : 'hardware', sales : 12000, day : 'Thursday'},
{department : 'outdoor', sales : 18007, day : 'Thursday'},
{department : 'carpentry', sales : 6109, day : 'Thursday'},
{department : 'hardware', sales : 7005, day : 'Friday'},
{department : 'outdoor', sales : 12006, day : 'Friday'},
{department : 'carpentry', sales : 16109, day : 'Friday'},
],

deptMap = salesData.reduce((p,c) => p[c.department] ? (p[c.department].push({sales: c.sales,
day: c.day}),p)
: (p[c.department] = [{sales: c.sales,
day: c.day}],p) ,{});
console.log(deptMap);

关于javascript - 困扰为什么 split 功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40523596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com