PHP合并首元素相同的数组元素并累加第二个元素
Got it, let's solve this problem where you need to merge entries in your array that share the same date, then sum up their corresponding visit counts. This is a super common data aggregation task, and here are a couple of clean, practical ways to do it in JavaScript:
Method 1: Use Array.reduce() (Most Concise)
This is the go-to approach for this kind of data transformation—it lets you iterate through the array once and build up your aggregated result as you go.
const rawData = [["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 7",1],["Apr 7",1],["Apr 7",1],["Apr 13",1],["Apr 14",1],["Apr 15",1],["Apr 15",1],["Apr 15",1],["Apr 16",1],["Apr 16",1],["Apr 16",1],["Apr 16",1],["Apr 16",1],["Apr 16",1],["Apr 16",1],["Apr 17",1],["Apr 17",1],["Apr 17",1]]; const aggregatedData = Object.entries( rawData.reduce((acc, [date, count]) => { // If the date already exists in the accumulator, add the count; otherwise set it acc[date] = (acc[date] || 0) + count; return acc; }, {}) ); console.log(aggregatedData); // Output: [["Apr 6",12], ["Apr 7",3], ["Apr 13",1], ["Apr 14",1], ["Apr 15",3], ["Apr 16",7], ["Apr 17",3]]
How this works:
- We start with an empty object (
{}) as our accumulator (acc). - For each entry in
rawData, we destructure the date and count. - We check if the date is already a key in the accumulator: if yes, we add the current count to the existing value; if not, we set it to the current count (falling back to 0 if it doesn't exist).
- Finally, we use
Object.entries()to convert the accumulator object back into the array format you need.
Method 2: Use a Loop (More Explicit for Beginners)
If you prefer a more step-by-step approach that's easier to follow at first, a simple for loop works great too:
const rawData = [["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 6",1],["Apr 7",1],["Apr 7",1],["Apr 7",1],["Apr 13",1],["Apr 14",1],["Apr 15",1],["Apr 15",1],["Apr 15",1],["Apr 16",1],["Apr 16",1],["Apr 16",1],["Apr 16",1],["Apr 16",1],["Apr 16",1],["Apr 16",1],["Apr 17",1],["Apr 17",1],["Apr 17",1]]; const tempObj = {}; // Loop through each entry to build the aggregated object for (const [date, count] of rawData) { if (tempObj[date]) { tempObj[date] += count; } else { tempObj[date] = count; } } // Convert the object back to the desired array format const aggregatedData = Object.entries(tempObj); console.log(aggregatedData); // Same output as above
Both methods will give you exactly what you need: a condensed array where each unique date is paired with the total number of visits on that day.
内容的提问来源于stack exchange,提问作者Zach Handley

