2

If I have some models like this

App.Transaction = DS.Model.extend({
    amount: DS.attr('number'),
    type: DS.attr('string')
});

where type can be something like "VISA" or "Mastercard" or "Cash". I have a computed property that calculates the total amount of all transactions.

totalAmount:function() {
    return this.getEach('amount').reduce(function(accum, item) {
        return (Math.round(accum*100) + Math.round(item*100))/100;
    }, 0);
}.property('@each')

What I want to do is create another computed property that returns the total amount of all transactions grouped by type (eg. total amount of all transactions with type == "VISA").

How do I do this in Ember js? is there a getAll method or some way to get all the transaction objects in an array that I can filter?

Devin Crossman
  • 7,454
  • 11
  • 64
  • 102

1 Answers1

2

The Ember.Array class has the filterProperty method which can do this for you. You can call this specifically like:

visaTotalAmount: function() {
    return this.filterProperty('type', 'VISA').getEach('amount').reduce(function(accum, item) {
        return (Math.round(accum*100) + Math.round(item*100))/100;
    }, 0);
}.property('@each')

This would filter out just the VISA type and do the total calculation as you did before.

gbabiars
  • 575
  • 3
  • 7