Fashion Inventory Average

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
var inventory = [
  {
    name: 'Brunello Cucinelli',
    shoes: [
      {name: 'tasselled black low-top lace-up', price: 1000},
      {name: 'tasselled green low-top lace-up', price: 1100},
      {name: 'plain beige suede moccasin', price: 950},
      {name: 'plain olive suede moccasin', price: 1050}
    ]
  },
  {
    name: 'Gucci',
    shoes: [
      {name: 'red leather laced sneakers', price: 800},
      {name: 'black leather laced sneakers', price: 900}
    ]
  }
];

var expected = {
  'designers': [
    {
      'name': 'Brunello Cucinelli',
      'averagePrice': 1025
    },
    {
      'name': 'Gucci',
      'averagePrice': 850
    }
  ]
};

function renderAveragePrices(currentInventory) {
  var designers = getDesigners(currentInventory);
  designers.forEach(function(designer) {
    var avgPrice = getAveragePrices(designer.name, currentInventory);
    designer['averagePrice'] = avgPrice;
  });
  return {'designers': designers};
}

function getDesigners(currentInventory) {
  var designers = [];
  for (var key in currentInventory) {
    designers.push({ name: currentInventory[key].name});
  }
  return designers;
}

function getAveragePrices(designer, currentInventory) {
  var prices = [];
  for (var key in currentInventory) {
    if (currentInventory[key].name === designer) {
      currentInventory[key].shoes.forEach(function(shoe) {
        prices.push(shoe.price);
      });
    }
  }

  var totalPrice = prices.reduce(function(a, b) {
    return a + b;
  });

  return totalPrice / prices.length;
}

console.log(expected);
// console.log(getDesigners(inventory));
// console.log(getAveragePrices('Brunello Cucinelli', inventory));
console.log(renderAveragePrices(inventory));