Reputation: 841
I've been looking at tutorials on the reduce() method in javascript, and after trying one of the use cases out on an array of objects, my code (although it seems to be formatted exactly the same as the one in the video, save for a different array) doesn't work the same way.
In the video, the instructor's function gets the eye colour for the characters in his array and adds a total amount of each colour. I've tried to do the same for "fuelType" in my spaceship array, and yet I get zeros for the total amount when I try it i my browser console.
Can anyone tell me why this would be?
let spaceships = [{
homePlanet: 'Earth',
color: 'silver',
fuelType: 'Turbo Fuel',
numCrew: 5,
flightPath: ['Venus', 'Mars', 'Saturn']
},
{
homePlanet: 'Venus',
color: 'space gray',
fuelType: 'Rocket Fuel',
numCrew: 4,
flightPath: ['Venus', 'Pluto', 'Saturn']
},
{
homePlanet: 'Neptune',
color: 'gold',
FuelType: 'Diesel',
numCrew: 7,
flightPath: ['Mercury', 'Mars', 'Jupiter']
},
{
homePlanet: 'Earth',
color: 'silver',
fuelType: 'Gasoline',
numCrew: 2,
flightPath: ['Saturn', 'Mars', 'Venus']
},
{
homePlanet: 'Earth',
color: 'silver',
fuelType: 'Rocket Fuel',
numCrew: 8,
flightPath: ['Saturn', 'Saturn', 'Jupiter']
},
{
homePlanet: 'Jupiter',
color: 'space gray',
fuelType: 'Turbo Fuel',
numCrew: 3,
flightPath: ['Jupiter', 'Mercury', 'Venus']
},
];
const totalFuelType = spaceships.reduce(function(acc, cur) {
const fuel = cur.fuelType;
if (acc[fuel]) {
acc[fuel]++;
} else acc[fuel] = 0;
return acc;
}, {});
console.log(totalFuelType);
Upvotes: 1
Views: 48
Reputation: 46
Try to add below code instead of if/else statement:
Below line will set 0 to acc[fuel] in case when its actually value is nullish (null or undefined):
acc[fuel] ??= 0;
and then increment its value:
acc[fuel]++;
let spaceships = [{
homePlanet: 'Earth',
color: 'silver',
fuelType: 'Turbo Fuel',
numCrew: 5,
flightPath: ['Venus', 'Mars', 'Saturn']
},
{
homePlanet: 'Venus',
color: 'space gray',
fuelType: 'Rocket Fuel',
numCrew: 4,
flightPath: ['Venus', 'Pluto', 'Saturn']
},
{
homePlanet: 'Neptune',
color: 'gold',
fuelType: 'Diesel',
numCrew: 7,
flightPath: ['Mercury', 'Mars', 'Jupiter']
},
{
homePlanet: 'Earth',
color: 'silver',
fuelType: 'Gasoline',
numCrew: 2,
flightPath: ['Saturn', 'Mars', 'Venus']
},
{
homePlanet: 'Earth',
color: 'silver',
fuelType: 'Rocket Fuel',
numCrew: 8,
flightPath: ['Saturn', 'Saturn', 'Jupiter']
},
{
homePlanet: 'Jupiter',
color: 'space gray',
fuelType: 'Turbo Fuel',
numCrew: 3,
flightPath: ['Jupiter', 'Mercury', 'Venus']
},
];
const totalFuelType = spaceships.reduce(function(acc, cur) {
const fuel = cur.fuelType;
acc[fuel] ??= 0;
acc[fuel]++;
return acc;
}, {});
console.log(totalFuelType);
Upvotes: 1