1

I have an array like the following:

var result=[{"id": 1, "details": [{"ah": 1.0, "dId": 11},{"ah": 2.0, "dId": 11}, {"ah": 2.0, "dId": 12}]}, {"id": 2, "details": [{"ah": 1.0, "dId": 11},{"ah": 2.0, "dId": 11}]}]

Now I would like to filter it by the Id and dId-properties using underscore.js, eg. giving me all details for id=1 and dId=11 and doing a sum of the ah-properties. So eg. filtering for id=1 and dId=11 should return 3.

I tried something like this: _.where(result, {id: 1, details.dId:11})

But I couldn't get it to work.

I created a fiddle: http://jsfiddle.net/j9Htk/

Any help is appreciated

thanks

Thomas

3 Answers 3

3

First filter the results to get those that have a matching id (can handle more the one with the same id):

var filteredList = _.filter(result, function(value){
    return value.id == 1;
});

Now sum the sums of all the ahs:

var sum = _.reduce(filteredList , function(memo, value){

    // find all details that have a matching dId
    var details = _.filter(value.details, function(detail){ return detail.dId == 11; });

    // return the sum of all the found details
    return memo + _.reduce(details, function(memo2, detail){ return memo2 + detail.ah; }, 0);

}, 0);
Sign up to request clarification or add additional context in comments.

Comments

0

I'm a beginner at underscore, here's my try:

var result=[{"id": 1, "details": [{"ah": 1.0, "dId": 11},{"ah": 2.0, "dId": 11}, {"ah": 2.0, "dId": 12}]}, {"id": 2, "details": [{"ah": 1.0, "dId": 11},{"ah": 2.0, "dId": 11}]}];


function calculate( result, id, dId ){

      var sum = 0;
      _.each( result[id].details, function( detail ){
        if( detail.dId == dId ){
            sum += detail.ah;
        }
      });

      console.log( 'id: ' + id + ' sum: ' + sum );
}

calculate( result,1,11 );

Comments

0
function extractSumOfAhs(result, id, dId) {
  return _.reduce(
    _.pluck(
      _.where(
        _.flatten(
          _.pluck(
            _.where(
              result,
              { id: id }
            ),
            "details"
          )
        ),
        {dId: dId}
      ),
      "ah"
    ),
    function(a,b) { return a + b; }
  )
}

or with chain:

function extractSumOfAhs(result, id, dId) {
  return _.chain(result)
    .where({id : id})
    .pluck("details")
    .flatten()
    .where({dId : dId})
    .pluck("ah")
    .reduce(function(a, b) { return a + b;})
    .value()  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.