Home > Mobile >  how to return people from an array born between certain ages with a function
how to return people from an array born between certain ages with a function

Time:08-22

I'm pretty new with js, and I'm trying to filter out people born between certain ages with a function using .filter

const allCoders = [
  {name: 'Ada', born: 1816},
  {name: 'Alice', born: 1990},
  {name: 'Susan', born: 1960},
  {name: 'Eileen', born: 1936},
  {name: 'Zoe', born: 1995},
  {name: 'Charlotte', born: 1986},
]

const findCodersBetween = (coders, startYear, endYear) => {
  allCoders.filter(coders = born > startYear && born > endYear)
  return coders
}

CodePudding user response:

Made small corrections to the return and function to filter

const findCodersBetween = (coders, startYear, endYear) => {
  return coders.filter((coder) => coder.born > startYear && coder.born < endYear);
};

You can also shorten this to

const findCodersBetween = (coders, startYear, endYear) => coders.filter(({born}) => born > startYear && born < endYear);

CodePudding user response:

You may follow this approach

const allCoders = [
  {name: 'Ada', born: 1816},
  {name: 'Alice', born: 1990},
  {name: 'Susan', born: 1960},
  {name: 'Eileen', born: 1936},
  {name: 'Zoe', born: 1995},
  {name: 'Charlotte', born: 1986},
]



const findCodersBetween = (coder) => {
  return coder["born"] >= startYear && coder['born'] <= endYear
} 


const startYear = 1800 
const endYear = 1950

const coders = allCoders.filter(findCodersBetween)
//console.log(coders)
return coders
  • Related