Home > OS >  how to return only the names of the people from an array born between certain ages with a function
how to return only the names of the people from an array born between certain ages with a function

Time:09-09

This is the code I'm currently working with. For an example "findCodersBetween(coders, 1960, 1986)" would return "[{name: 'Alice', born: 1990}, {name: 'Susan', born: 1960}, {name: 'Charlotte', born: 1986}]". But what I want is for the function to only output the names "['Alice', 'Susan', 'Charlotte']". I think the answer is simple I just can't figure it out.

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) => {
  return coders.filter((coder) => coder.born >= startYear && coder.born <= endYear);
};

CodePudding user response:

You can use map and return only the name: .map(coder => coder.name)

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) => {
  return coders.filter((coder) => coder.born >= startYear && coder.born <= endYear).map(coder => coder.name);
};

console.log(findCodersBetween(allCoders, 1960, 1986))

CodePudding user response:

Since filter returns the objects that match the condition (note that "Alice" wouldn't be returned in your example as 1990 is greater than 1986) you need to map over the returned array of objects and, for each coder, return just the name from the object.

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) => {
  return coders.filter(coder => {
    return coder.born >= startYear && coder.born <= endYear;
  }).map(coder => coder.name);
}

console.log(findCodersBetween(allCoders, 1960, 1986));

  • Related