Higher order function filter

I came across an example explaining higher order functions. here is the example:
Let’s say we have an array which contains objects with name and age properties. We want to create an array that contains only the persons with full age (age greater than or equal to 18).
Without Higher-order function:

const persons = [
{ name: ‘Peter’, age: 16 },
{ name: ‘Mark’, age: 18 },
{ name: ‘John’, age: 27 },
{ name: ‘Jane’, age: 14 },
{ name: ‘Tony’, age: 24},
];
const fullAge = ;
for(let i = 0; i < persons.length; i++) {
if(persons[i].age >= 18) {
fullAge.push(persons[i]);
}
}
console.log(fullAge);

I understand this perfectly and lets say if I want to push only the name of people who are >= 18 we just need to change the line to :
fullAge.push(persons[i].name);

here the writer wrote the same cod WITH Higher order function:
const persons = [
{ name: ‘Peter’, age: 16 },
{ name: ‘Mark’, age: 18 },
{ name: ‘John’, age: 27 },
{ name: ‘Jane’, age: 14 },
{ name: ‘Tony’, age: 24},
];
const fullAge = persons.filter(person => person.age >= 18);
console.log(fullAge);

I understand this as well. My question is:
what if we want to only push the name of people >=18 to the new array using higher order function.

It will require an additional step. The .filter method is going to return the elements of the original array that pass your test. You could chain a .map method to the end that only returns the name property. The code looks clean, but in reality the original code using the for loop is more efficient since it only iterates through the array once.

Hint
const fullAge = persons.filter(person => person.age >= 18).map(person => person.name);
// filters the original array, and then iterates through the filtered array to create
// a new array with only the names, so you create 2 new arrays rather than 1, 
// and iterate twice
2 Likes

@bigly87 You can do it in one pass of the array with a higher order function but you would use the reduce method (useful for a lot of different things). It can perform both filter and map in one pass of the array. It essentially starts with an empty array (in this example) and fills this up with the names of persons where age >= 18. But a for loop is also a good way to do it. The array we are filling up is passed into the callback as prev and the current value is referenced in the callback by the name cur.

const fullAge = persons.reduce((prev, cur) => cur.age >= 18 ? [...prev, cur.name] : prev, []);

But I will add that a for-loop as @midlindner suggested is the fastest approach. The higher order array methods are typically slower. Using the callback and so on has a cost. But most of the time the speed difference won’t matter unless the array is really huge.