Search code examples
javascriptdry

Is it possible to reduce my code anymore?


Here's my code.

function legalPeopleToDrive(people) {
  const myFilter = people
    .filter(p => p.age > 14)
    .map(p => {
      return p.name;
    });
  return myFilter;
}

const myObj = [
  { name: "John", age: 14 },
  { name: "Jim", age: 16 },
  { name: "Ben", age: 18 }
];

console.log(legalPeopleToDrive(myObj));

Pretty much, I'm just really curious as to see if it's possible to reduce this anymore. Can this be done also by just using one of these methods filter() or map()?


Solution

  • You can create the desired result by only iterating over the array once, which might be done with .reduce. You can also immediately return the call of the array method - no need to store it in a variable beforehand. Another option is to use an arrow function for concise return:

    const legalPeopleToDrive = people => people.reduce((a, p) => {
      if (p.age > 14) a.push(p.name);
      return a;
    }, []);
    
    const myObj = [
      { name: "John", age: 14 },
      { name: "Jim", age: 16 },
      { name: "Ben", age: 18 }
    ];
    
    console.log(legalPeopleToDrive(myObj));

    Still, your current code looks fine to me.