$.array.calculate

Calculate method of array helpers

You may want to calculate some of properties inside an object and then store it to a new property or update the current empty property. Here we provide calculate helper with 3 arguments such as array of objects, new property, and callback function. Also, on callback parameter, we only allow to access the parameter from property with number type only, that mean that helper will exclude all the property with other type.

$.array.calculate(fromArray, newProperty, callbackFunction)

// Example:
const fromArray = [
  { name: 'Item-1', quantity: 6, price: 12, total: 0 },
  { name: 'Item-2', quantity: 5, price: 7.5, total: 0 },
  { name: 'Item-3', quantity: 3, price: 4 },
  { name: 'Item-4', quantity: 7, price: 9.6 }
]

$.array.calculate(fromArray, 'total', (quantity, price) => {
  return Number(quantity) * Number(price)
})

//=> [
//  { name: 'Item-1', quantity: 6, price: 12, total: 72 },
//  { name: 'Item-2', quantity: 5, price: 7.5, total: 37.5 },
//  { name: 'Item-3', quantity: 3, price: 4, total: 12 },
//  { name: 'Item-4', quantity: 7, price: 9.6, total: 67.2 }
//]

Last updated