So I have this array of pilots :
var pilots = [
{
id: 10,
name: "Poe Dameron",
years: 14,
},
{
id: 2,
name: "Temmin 'Snap' Wexley",
years: 30,
},
{
id: 41,
name: "Tallissan Lintra",
years: 16,
},
{
id: 99,
name: "Ello Asty",
years: 22,
}
];
And I want to print the most experienced pilot. By using reduce() I can print the most experienced one. But this reduce function will print the last pilot with most experience. In the above array the reduce works perfectly:
var mostExpPilot = pilots.reduce(function (oldest, pilot) {
return (oldest.years || 0) > pilot.years ? oldest : pilot;
}, {});
console.log(mostExpPilot); // Prints { id: 2, name: 'Temmin \'Snap\' Wexley', years: 30 }
If we have 2 or more pilots with the same experience and I want to print both occurrences. For example we have the below array where there are two pilots with the same years of experience. The reduce function that is implemented it prints only the last pilot.
var pilots = [
{
id: 10,
name: "Poe Dameron",
years: 14,
},
{
id: 2,
name: "Temmin 'Snap' Wexley",
years: 30,
},
{
id: 41,
name: "Tallissan Lintra",
years: 30,
},
{
id: 99,
name: "Ello Asty",
years: 22,
}
];
//find the most experienced pilot
var mostExpPilot = pilots.reduce(function (oldest, pilot) {
return (oldest.years || 0) > pilot.years ? oldest : pilot;
}, {});
console.log(mostExpPilot); // prints { id: 41, name: 'Tallissan Lintra', years: 30 }
Can I do it with reduce() ? If yes, could you please let me know? If no, how can I do that? Thanks.**