reduce()
by Cristi Salcescu
JavaScript
let shoppingList = [
{ name : "orange", units : 2, price : 10, type : "FRT"},
{ name : "lemon", units : 1, price : 15, type : "FRT"},
{ name : "fish", units : 0.5, price : 30, type : "MET"}
];
//imperative
var totalPrice = 0,
fruitsPrice = 0;
for(let i=0; i<shoppingList.length; i++){
let line = shoppingList[i];
totalPrice += line.units * line.price;
if(line.type === "FRT"){
fruitsPrice += line.units * line.price;
}
}
console.log(totalPrice);
console.log(fruitsPrice);
//functional
function addPrice(totalPrice, line){
return totalPrice + (line.units * line.price);
}
function areFruits(line){
return line.type === "FRT";
}
var totalPrice = shoppingList.reduce(addPrice, 0);
var fruitsPrice = shoppingList.filter(areFruits).reduce(addPrice, 0);
console.log(totalPrice);
console.log(fruitsPrice);