Skip to content

Instantly share code, notes, and snippets.

@JoseJuan81
Created September 28, 2018 14:33
Show Gist options
  • Save JoseJuan81/d297ced7088ea5603836c3c75fbf9c92 to your computer and use it in GitHub Desktop.
Save JoseJuan81/d297ced7088ea5603836c3c75fbf9c92 to your computer and use it in GitHub Desktop.

Because sometimes one person can be the voice of the whole office! Yes! The best and most popular quiz in the whole Independencia Av. is back!

This is a easy one for the loop lovers!

From this array you must return an object with the following data:

The total amount Total quantity of items. Total amount per type Quantity of items per type Rules You cannot use for, forEach, map or filter. The structure of the array is an example, it must work with any quantity of items and different values for the type property. The final object only can have 2 properties plus the quantity of different types. It means from the above example your result object only can have 5 properties

{
  total: 0,
  quantity: 0,
  type1: ...
  type2: ...
  type3: ...
}
var data = [
  {
    "amount": 100,
    "type": 1
  },
  {
    "amount": 900,
    "type": 2
  },
  {
    "amount": 80,
    "type": 2
  },
  {
    "amount": 200,
    "type": 3
  },  
  {
    "amount": 300,
    "type": 1
  }  
]

function tran(obj, item, index, arr) {
  if (!obj.quantity) {
    obj.quantity = arr.length;
    obj.totalAmount = 0;
  }
  var byType = `type${item.type}`;
  if (obj[byType]) {
    obj[byType].quantity += 1;
    obj[byType].amount += item.amount;
  } else {
    obj[byType] = {
      quantity: 1,
      amount: item.amount,
    }
  }
  obj.totalAmount += item.amount;
  return obj;
}

var r = data.reduce(tran, {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment