Home > Net >  Use callback to check and return an object from the array
Use callback to check and return an object from the array

Time:01-06

What is the best way to get { city: "Malden", population: 2200 } if I console.log(smallPop(array, callback) Using reduce, filter or find, not sort method.

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

CodePudding user response:

I would expect a function called minBy to accept also a desired property like... "population" i.e: minBy(arr, prop) The cb is useless, since I'd also expect such function to return the needed

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);

CodePudding user response:

Just replace:

array.map(element => element.population)

With:

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

That should do it, as in the demo below:

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) );

  • Related