JS(ES6):按对象属性聚合数组,统计年度水果数量及总数
reduce Hey there! Let's break down how to use ES6's reduce method to aggregate your fruit array exactly as you need it. This method is ideal for grouping and counting data like this—let's jump right in.
First, here's your original data for reference:
const fruits = [ { fruit: 'apple', year: 2018 }, { fruit: 'apple', year: 2018 }, { fruit: 'banana', year: 2018 }, { fruit: 'orange', year: 2018 }, { fruit: 'apple', year: 2017 }, { fruit: 'apple', year: 2016 } ];
The Approach
We'll use reduce to build an intermediate object where each key is a year, and the value is an object containing the year, counts for each fruit, and the total number of entries. Then we'll convert that object's values into the array format you want.
Full Code Solution
const aggregatedData = fruits.reduce((accumulator, currentItem) => { // Check if we already have an entry for the current year if (!accumulator[currentItem.year]) { // If not, initialize a new entry with the year and total starting at 0 accumulator[currentItem.year] = { year: currentItem.year, total: 0 }; } // Increment the count for the current fruit (initialize to 1 if it's the first occurrence) accumulator[currentItem.year][currentItem.fruit] = (accumulator[currentItem.year][currentItem.fruit] || 0) + 1; // Increment the total count for the year accumulator[currentItem.year].total += 1; return accumulator; }, {}); // Convert the intermediate object into the final array format const result = Object.values(aggregatedData);
What This Does
- Initialization: We start with an empty object
{}as thereduceaccumulator. - Year Check: For each fruit entry, we check if the year already exists in our accumulator. If not, we create a new entry with the year and set
totalto 0. - Fruit Count: We increment the count for the specific fruit—using
(value || 0)ensures we don't getNaNif the fruit hasn't been counted for that year yet. - Total Count: We add 1 to the year's total each time we process an entry.
- Final Conversion:
Object.values()takes all the values from our intermediate object and turns them into the array structure you requested.
The Result
Running this code will give you exactly the output you're looking for:
[ { year: 2018, apple: 2, banana: 1, orange: 1, total: 4 }, { year: 2017, apple: 1, total: 1 }, { year: 2016, apple: 1, total: 1 } ]
This approach is efficient too—we only loop through the original array once, so it runs in O(n) time complexity.
Hope this helps! Feel free to ask if you want to dive deeper into any part of this solution.
内容的提问来源于stack exchange,提问作者Nibor

