使用reduce构建比较两个数组的数组对象



我正在尝试填充一个图,数据必须以特定的方式格式化。我终于把数据做成了正确的形状,但我意识到我缺少了值。

所以我有一系列日期:

const labels = ["Sep.08", "Sep.09", "Sep.12", "Sep.13", "Sep.14"]

我有一个包含namedate以及count:的对象数组

const Data = [
{date: "Sep.08", name: "User1", count: 8},
{date: "Sep.08", name: "User2", count: 2},
{date: "Sep.09", name: "User2", count: 3},
{date: "Sep.09", name: "User3", count: 1},
{date: "Sep.12", name: "User1", count: 11},
{date: "Sep.13", name: "User1", count: 3},
{date: "Sep.13", name: "User2", count: 3},
{date: "Sep.14", name: "User2", count: 7},
]

我正在努力实现的目标:

  1. 每个名称在新对象中都应该有一个数组
  2. 每个日期都应该在数组中表示,这样每个数组长度相同。如果用户没有表示日期,则应在新数组中的该索引处添加一个零

我的预期结果是:

const result = {
User1: [8,0,11,3,0], //0's where user has no object with the dates of "Sep.09" & "Sep.14"
User2: [2,3,0,3,7],
User3: [0,1,0,0,0],
}

我正在使用.reduce创建我的新对象:

const Data = [
{date: "Sep.08", name: "User1", count: 8},
{date: "Sep.08", name: "User2", count: 2},
{date: "Sep.09", name: "User2", count: 3},
{date: "Sep.09", name: "User3", count: 1},
{date: "Sep.12", name: "User1", count: 11},
{date: "Sep.13", name: "User1", count: 3},
{date: "Sep.13", name: "User2", count: 3},
{date: "Sep.14", name: "User2", count: 7},
]
const labels = ["Sep.08", "Sep.09", "Sep.12", "Sep.13","Sep.14"]

const groups = Data.reduce((acc, obj) => {

if (!acc[obj.name]) {
acc[obj.name] = [];
}

acc[obj.name].push(obj.count);
return acc;
}, {});
console.log(groups)

问题是我不知道如何将标签与acc对象中的名称进行比较。Reduce让我很困惑,但它似乎是按照我需要的方式格式化数据的最干净的方法。任何建议都会有帮助。

您可以这样做:

const Data = [{date:"Sep.08",name:"User1",count:8},{date:"Sep.08",name:"User2",count:2},{date:"Sep.09",name:"User2",count:3},{date:"Sep.09",name:"User3",count:1},{date:"Sep.12",name:"User1",count:11},{date:"Sep.13",name:"User1",count:3},{date:"Sep.13",name:"User2",count:3},{date:"Sep.14",name:"User2",count:7},];
const labels = ["Sep.08","Sep.09","Sep.12","Sep.13","Sep.14"];
const groups = Data.reduce((acc, { date, name, count }) => {
if (!acc[name]) {
// Fill an array with zeroes, the length of labels
acc[name] = labels.map(_ => 0);
}
// Find the index of the current label
const labelIndex = labels.indexOf(date);
// Replace the corresponding zero
acc[name][labelIndex] = count;

return acc;
}, {});

console.log(groups);

我会进行第一个循环来查找所有日期和用户。然后,对于每个日期,在用户上循环以构建他们的数组。

const dictionary = {};
const users = new Set();
Data.forEach(({date, name, count}) => {
if (!dictionary[date]) dictionary[date] = {};
// for each date, store users and their count when available
dictionary[date] = {[name]: count};
// keep track of existing users
users.add(name);
}
const result = {};
// convert the user set to an array
const userArray = Array.from(users);
// populate an array of count for each user
userArray.forEach(user => result[user] = []);
Object.entries(dictionary).forEach(([date, userCountMap]) => {
userArray.forEach(user => {
// for each date, populate the count of each user, or put 0 if there is no count
result[user].push(userCountMap[user] || 0);
});
});
console.log(result);

最新更新