DEV Community

bomoniyi
bomoniyi

Posted on • Edited on

Using If statements with .reduce()

const cars = [
  { name: "Toyota", isElectric: false, weight: 1320 },
  { name: "Ford", isElectric: false, weight: 1400 },
  { name: "Volkswagen", isElectric: false, weight: 1370 },
  { name: "Honda", isElectric: false, weight: 1375 },
  { name: "Tesla", isElectric: true, weight: 1750 },
  { name: "BMW", isElectric: true, weight: 1350 },  
];


const totalWeight = cars.reduce((accumulator, car) => {
    if (car.isElectric) {
        return accumulator + car.weight;
    } else {
        return accumulator;
    }
}, 0)

console.log(totalWeight);
Enter fullscreen mode Exit fullscreen mode

or following FP principles:

const cars = [
  { name: "Toyota", isElectric: false, weight: 1320 },
  { name: "Ford", isElectric: false, weight: 1400 },
  { name: "Volkswagen", isElectric: false, weight: 1370 },
  { name: "Honda", isElectric: false, weight: 1375 },
  { name: "Tesla", isElectric: true, weight: 1750 },
  { name: "BMW", isElectric: true, weight: 1350 },  
];


const totalWeight = cars.filter(car => car.isElectric).reduce((accumulator, car) => {
        return accumulator + car.weight;
}, 0)

console.log(totalWeight);
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
crisz profile image
crisz

To follow the FP principles, it should be cars.filter(...).reduce(...)

Collapse
 
bomoniyi profile image
bomoniyi

Thanks! Updated:

const cars = [
  { name: "Toyota", isElectric: false, weight: 1320 },
  { name: "Ford", isElectric: false, weight: 1400 },
  { name: "Volkswagen", isElectric: false, weight: 1370 },
  { name: "Honda", isElectric: false, weight: 1375 },
  { name: "Tesla", isElectric: true, weight: 1750 },
  { name: "BMW", isElectric: true, weight: 1350 },  
];


const totalWeight = cars.filter(car => car.isElectric).reduce((accumulator, car) => {
        return accumulator + car.weight;
}, 0)

console.log(totalWeight);
Enter fullscreen mode Exit fullscreen mode