如何统一数组结构?补全人员月度任务执行数数组方法咨询
Got it, let's work through this problem together. Your goal is to take an array of partial monthly task counts and expand it so every person has entries for all 12 months—filling in 0 for any month where there's no existing data for that person. Here's a step-by-step solution using JavaScript (the logic translates easily to other languages too):
Step 1: Group Data by Person
First, we need to organize the original data so all entries for the same person are grouped together. We'll use a unique key (combining first and last name) to avoid mixing up people with identical first/last names.
const originalData = [ ["Ilhem", "Ben Salah", 4, 1], ["Ilhem", "Ben Salah", 3, 2], ["Ilhem", "Ben Salah", 3, 3], ["Ilhem", "Ben Salah", 3, 4], ["Sghaier", "Mahmoud", 1, 1] ]; // Group entries by full name (first + last) const personGroups = {}; originalData.forEach(entry => { const [firstName, lastName, taskCount, month] = entry; const uniqueKey = `${firstName}_${lastName}`; // Initialize the group if it doesn't exist if (!personGroups[uniqueKey]) { personGroups[uniqueKey] = { firstName, lastName, monthlyCounts: {} // Stores { month: taskCount } pairs }; } // Save the task count for the specific month personGroups[uniqueKey].monthlyCounts[month] = taskCount; });
Step 2: Generate Full 12-Month Entries
Next, we'll loop through each person's group and create entries for every month from 1 to 12. For months with existing data, we'll use the original task count; for missing months, we'll default to 0.
const fullYearData = []; // Iterate over each person in our grouped data Object.values(personGroups).forEach(person => { for (let month = 1; month <= 12; month++) { // Use existing count if available, else 0 const taskCount = person.monthlyCounts[month] || 0; fullYearData.push([person.firstName, person.lastName, taskCount, month]); } }); console.log(fullYearData);
Quick Note on Your Example Target Data
I noticed in your provided target array, Ilhem's month 2 entry uses 0—but your original data has a task count of 3 for that month. The code above preserves the original task count for existing months. If that was a typo in your example, the code will output the correct values. If you intended to overwrite existing counts for some reason, we can adjust the logic to prioritize 0 instead of original values.
How This Logic Works
- Grouping: The
personGroupsobject keeps track of each person's known monthly task counts, making it straightforward to check which months are missing. - Filling Missing Months: By looping from 1 to 12, we guarantee every month is covered. The
|| 0operator handles missing months by defaulting to0cleanly.
内容的提问来源于stack exchange,提问作者majd hwas

