You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 reduce operation (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

  1. Counting Years:

    • We use reduce to 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 reduce works correctly.
  2. Finding the Most Frequent Year:

    • Object.entries(yearCounts) converts the count object into an array of [year, count] pairs.
    • Another reduce call 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.entries returns 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 03:12:18