locked
underscorejs RRS feed

  • Question

  • User1519602350 posted

    Countby category based on userId using undersocrejs.

    Please refer the below script, its printing the value "Technology:2" & "Analytics:1".

    Expected answer: "Technology:1" & "Analytics:1" because both the 'Technology' objects are the same userId ie. 1

    arrayFlatten = [
          {
            area:"Digital",
            category:"Technology",
            userId:1,
            weightedAverage:10
          },
          {
            area:"Digital",
            category:"Technology",
            userId:1,
            weightedAverage:20
          },
          {
            area:"Digital",
            category:"Analytics",
            userId:2,
            weightedAverage:30
          }
    ]
    var types = _.groupBy(arrayFlatten, 'category');
    console.log(types);
    var result = {};
    _.each(types, function(val, key) {
      console.log(key+" "+val.length);
    });
    console.log(result);
    

    Thanks

    Thursday, September 1, 2016 6:27 PM

Answers

  • User1724605321 posted

    Hi ssvikramuk,

    If you group By "category" , you will get two groups , one group is "Technology" has two items , one group is "Analytics" has one item . For example :

    _.groupBy(['one', 'two', 'three'], 'length');
    
    result:
    => {3: ["one", "two"], 5: ["three"]}

    Try the code in   https://forums.meteor.com/t/underscorejs-countby-category/28790 

    And here is a code sample for how to get unique property .Click here for code sample .

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 2, 2016 6:40 AM