Underscore - Additional Methods

SPA Tools extend Underscore by adding some new functions :
  • Sum
  • Average
  • Count
  • Select

Whe are using the array below on every samples in this page.
var sampleArray = [
    { ref: "TILICBASE", price: 10, quantity: 12 },
    { ref: "TIPRESPGE", price: 150, quantity: 4 },
    { ref: "TITMPLDES", price: 350, quantity: 1 },
    { ref: "TITRAINDAY", price: 500, quantity: 1 }
];

Sum

Sum is a function which return the sum of the result of iterator function on each element of the collection.

Sample:
_.sum(sampleArray, function(product) { return p.price * p.quantity; });
// 1570

Average

Average is a function which work like sum but return the average of every iterator function.

Sample:
_.average(sampleArray, function(product) { return p.price; });
// 252.5

Count

Return the length of the collection (object or array) filtered by the iterator function.

Sample:
_.count(sampleArray, function(product) { return p.price > 300; });
// 2

Select

Select is a combination of the original filter and map methods of Underscore. It allow transformation of result by applying a filter.

Sample:
_.select(sampleArray, function(product) { 
    if (product.price > 300)
        return { ref: product.ref, price: product.price };
});
// { ref: "TITMPLDES", price: 350 },
// { ref: "TITRAINDAY", price: 500 }

Last edited Dec 20, 2012 at 4:53 PM by SomaticIT, version 2

Comments

No comments yet.