Skip to content

Underscore Extension Methods Average

Maxime LUCE edited this page Apr 10, 2015 · 1 revision

Allow to create average by passing collection values using given iterator.

Usage

Introduction
var myArray = [
    { productId: 1, title: 'My Product 1', price: 10, quantity: 1 },
    { productId: 2, title: 'My Product 2', price: 15.5, quantity: 4 },
    { productId: 3, title: 'My Product 3', price: 7.25, quantity: 1 }
];
Simple usage
var averageQuantity = _.average(myArray, function(obj) { return obj.quantity; });
// averageQuantity  === 2
Complex usage
var averageByProduct = _.average(myArray, function(obj) { return obj.price * obj.quantity; });
// averageByProduct === 13.21 ...

Clone this wiki locally