使用ES6数组方法找出小行星发现次数最多的年份
Solution to Find the Most Frequent Asteroid Discovery Year
Issues with the Original Code
The provided code has three critical problems:
- Syntax Error: The parentheses around
(acc, val)are incorrectly placed before the arrow function, leading to invalid JavaScript syntax. - Incomplete Logic: The function only generates a count of occurrences per year but does not extract the year with the highest count.
- Accumulator Return: The arrow function does not return the accumulator object, breaking the
reduceoperation (each iteration would return the count value instead of updating the accumulator).
Corrected Code
function getGreatestDiscoveryYear(data) { // Step 1: Count how many asteroids were discovered each year const yearCounts = data.asteroids.reduce((acc, asteroid) => { const year = asteroid.discoveryYear; acc[year] = (acc[year] || 0) + 1; return acc; }, {}); // Step 2: Find the year with the highest discovery count const [mostFrequentYear] = Object.entries(yearCounts).reduce((maxEntry, currentEntry) => { return currentEntry[1] > maxEntry[1] ? currentEntry : maxEntry; }); return Number(mostFrequentYear); }
How It Works
Counting Years:
- We use
reduceto iterate over the asteroids array, building an object where keys are discovery years and values are the number of asteroids discovered that year. - For each asteroid, we increment the count for its discovery year (initializing to 0 if the year isn't already in the accumulator).
- We explicitly return the accumulator object after each update to ensure
reduceworks correctly.
- We use
Finding the Most Frequent Year:
Object.entries(yearCounts)converts the count object into an array of[year, count]pairs.- Another
reducecall compares each pair to find the one with the highest count. - We convert the year string back to a number before returning it (since
Object.entriesreturns keys as strings).
Test Result
When run with the provided asteroid data, this function returns 1847—the year with the most asteroid discoveries (3 asteroids: 6 Hebe, 7 Iris, 8 Flora).
内容的提问来源于stack exchange,提问作者OldsoulPhil
相关产品推荐
相关产品推荐

