Reputation: 15
I have an Array of Objects (Cars) :
var car = [
{speed: 20, color: "red"},
{speed: 5, color: "blue"},
{speed: 80, color: "yellow"},
{speed: 79, name: "orange"}
];
and a function that should return the fastest Car in the Array :
function getFastestCar(cars) {
cars.reduce(function (prevFastestCar,curFastestcar) {
if (curFastestcar.speed > prevFastestCar.speed) return curFastestcar;
else return prevFastestCar;
}, {speed: -Infinity, name: "test"});
};
After searching for a few hours I couldn´t find any solution why the function is returning undefined. I debugged the code and the function works perfectly fine, except in the last "step" it somehow replaces the fastest Car with undefined. I´m trying to understand the concept behind the reduce Method I know that there are easier ways to do this, but I´m curious why it is not working correctly.
Upvotes: 0
Views: 2265
Reputation: 581
This is probably just personal preference, but I don't like using Array.reduce for tasks involving comparison. I think the following is much easier to follow:
const cars = [
{speed: 20, color: "red"},
{speed: 5, color: "blue"},
{speed: 80, color: "yellow"},
{speed: 79, name: "orange"}
];
function getFastestCar(cars) {
var fastestCar = {};
if (cars.length) {
cars.forEach(car => {
fastestCar = fastestCar.speed > car.speed ? fastestCar : car;
});
}
return fastestCar;
}
console.log(getFastestCar(cars));
Upvotes: 0