javascript 使用callback检查并返回数组中的对象

irlmq6kh  于 2023-01-08  发布在  Java
关注(0)|答案(2)|浏览(140)

获取{ city:“马尔登”,人口:2200 } if I console.log(smallPop(array,callback)使用reduce、filter或find方法,而不是sort方法。

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) {
}
6rqinv9w

6rqinv9w1#

我希望一个名为minBy的函数也接受一个所需的属性,如... "population",即:cb是无用的,因为我也希望这样的函数return所需的

const minBy = (arr, prop) =>
  arr.reduce((prev, curr) => prev[prop] < curr[prop] ? prev : curr);

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

console.log("Min by population:", minBy(array, "population"));
console.log("Min city by area:", minBy(array, "area").city);
idv4meu8

idv4meu82#

只需更换:

array.map(element => element.population)

其中:

array.sort((a,b) => a.population - b.population)[0]

这样就可以了,如下面的演示所示:

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

function callback(array) {
  //sort from smallest population to largest
  //object with smallest population would be at index 0 ... [0]
  return array.sort((a,b) => a.population - b.population)[0];
}

function smallPop(array, callback) {
    return callback( array );
}

console.log( smallPop(array, callback) );

相关问题