Skip to content

Instantly share code, notes, and snippets.

@Ugarz
Last active October 9, 2019 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ugarz/8d19cbc820ab232eb9f695518fe30ea1 to your computer and use it in GitHub Desktop.
Save Ugarz/8d19cbc820ab232eb9f695518fe30ea1 to your computer and use it in GitHub Desktop.
Playing with Reduce

Reduce Practicing

const basket = [
  { "chanvre" : { "price": 23.39, "nb": 1 }},
  { "flapjack": { "price": 19.99, "nb": 2 }},
  { "farine"  : { "price": 19.99, "nb": 3 }}
];

const basket2 = [{
  "chanvre" : { "price": 23.39, "nb": 1 },
  "flapjack": { "price": 19.99, "nb": 2 },
  "farine"  : { "price": 19.99, "nb": 3 }
}];

const basket3 = {
  "products" : {
    "chanvre" : { "price": 23.39, "nb": 1 },
    "flapjack": { "price": 19.99, "nb": 2 },
    "farine"  : { "price": 19.99, "nb": 3 }
  }
};


//  basket 1
const fullPricebasket1 = basket.reduce((acc, curr) => {
  const currentKey = Object.keys(curr)[0]
  return acc + curr[currentKey].price
}, 0)


// basket2
const fullPricebasket2 = basket2.reduce((acc, curr) => {
  return acc + Object.keys(curr)
    .map(key => curr[key].price)
    .reduce((prices, currentPrice) => {
      return prices + currentPrice
    }, 0)
}, [])


console.log('Basket1 :', fullPricebasket1);
console.log('Basket2 :', fullPricebasket2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment