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

如何通过回调函数结合reduce/filter/find获取数组中人口最少的城市对象

问题:实现smallPop函数获取人口最少的城市对象

现有如下数组与回调函数,请编写smallPop函数,要求借助回调函数,结合reduce、filter或find方法(禁止使用sort方法),使console.log(smallPop(array, callback))能够输出{ city: "Malden", population: 2200 }。

原代码如下:

const array = [
  { city: "Malden", population: 2200 },
  { city: "Chelsea", population: 3000 },
  { city: "Cambridge", population: 5400 }
];

function callback(array) {
  return array.map(element => element.population)
}

function smallPop(array, callback) {
}

解决方案

实现思路

给定的callback会返回数组中所有城市的人口数值数组,我们可以先通过它拿到人口列表,找到最小值后用find匹配对应城市;或者结合reduce在遍历过程中直接对比人口大小,筛选出目标对象。

方式一:使用find方法(简洁直观)

function smallPop(array, callback) {
  // 借助callback获取所有城市的人口数组
  const populations = callback(array);
  // 找出人口最小值
  const minPopulation = Math.min(...populations);
  // 匹配人口等于最小值的城市对象
  return array.find(city => city.population === minPopulation);
}

方式二:使用reduce方法(单次遍历高效)

function smallPop(array, callback) {
  const populations = callback(array);
  // 遍历数组,始终保留人口最小的城市对象
  return array.reduce((minCity, currentCity, index) => {
    return populations[index] < populations[array.indexOf(minCity)] ? currentCity : minCity;
  }, array[0]);
}

两种方式均符合要求:借助了给定的callback,未使用sort方法,最终都能输出目标城市对象。

内容的提问来源于stack exchange,提问作者adn84

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:30:44