Search code examples
backbone.jsunderscore.js

Backbone JS find the minimum value


I have this json which populates my collection (TableListCollection) of models (TableModel)

{
    "tables": [
        {
            "tableId": 15,
            "size": 8,
            "occupiedSeats": 0,
            "stakes": {
                "smallBlindAmount": 10,
                "bigBlindAmount": 20,
                "minBuyInAmount": 20,
                "maxBuyInAmount": 200
            },
            "gameType": "HOLDEM",
            "gameSpeed": "NORMAL",
            "friends": []
        },
        {
            "tableId": 16,
            "size": 8,
            "occupiedSeats": 0,
            "stakes": {
                "smallBlindAmount": 20,
                "bigBlindAmount": 40,
                "minBuyInAmount": 20,
                "maxBuyInAmount": 200
            },
            "gameType": "HOLDEM",
            "gameSpeed": "NORMAL",
            "friends": []
        },
        {
            "tableId": 17,
            "size": 8,
            "occupiedSeats": 0,
            "stakes": {
                "smallBlindAmount": 40,
                "bigBlindAmount": 60,
                "minBuyInAmount": 20,
                "maxBuyInAmount": 200
            },
            "gameType": "HOLDEM",
            "gameSpeed": "NORMAL",
            "friends": []
        }
    ]
}

I want to find the table with the minimum smallBlindAmount.

I see that I can use the _.min() but I can't figure out what I have to pass as an iterator.

Thanks in advance.


Solution

  • Either directly on the JSON

    var json=...
    var min = _.min(json.tables,function(item) {
        return item.stakes.smallBlindAmount
    });
    console.log(min.stakes.smallBlindAmount);
    

    or on your collection

    var json=...
    var c=new Backbone.Collection(json.tables);
    var m=c.min(function(model) {
        return model.get("stakes").smallBlindAmount
    });
    console.log(m.get("stakes").smallBlindAmount);
    

    In both cases, the iterator is used to extract the values to be compared.