Sum javascript object propertyA values with same object propertyB in array of objects












10















How would one take a javascript array of objects such as:



my objArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:42},
{key:Mon Sep 24 2013 00:00:00 GMT-0400, val:78},
{key:Mon Sep 25 2013 00:00:00 GMT-0400, val:23},
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:54}]


and merge duplicate keys by summing the values.
In order to get something like this:



my reducedObjArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:96},
{key:Mon Sep 24 2013 00:00:00 GMT-0400, val:78},
{key:Mon Sep 25 2013 00:00:00 GMT-0400, val:23}]


I have tried iterating and adding to a new array, but this didn't work:



var reducedObjArr = ;
var item = null, key = null;
for(var i=0; i<objArr.length; i++) {
item=objArr[i];
key = Object.keys(item)[0];
item=item[key];

if(!result[key]){
result[key] = item;
}else{
result[key] += item;}
}a









share|improve this question























  • Why are you doing key = Object.keys(item)[0]; item=item[key]; ? You already know the name is key, so just do item.key or objArr[i].key. Also, using the [0] index won't necessarily always give you the same property.

    – user2736012
    Oct 7 '13 at 19:50


















10















How would one take a javascript array of objects such as:



my objArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:42},
{key:Mon Sep 24 2013 00:00:00 GMT-0400, val:78},
{key:Mon Sep 25 2013 00:00:00 GMT-0400, val:23},
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:54}]


and merge duplicate keys by summing the values.
In order to get something like this:



my reducedObjArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:96},
{key:Mon Sep 24 2013 00:00:00 GMT-0400, val:78},
{key:Mon Sep 25 2013 00:00:00 GMT-0400, val:23}]


I have tried iterating and adding to a new array, but this didn't work:



var reducedObjArr = ;
var item = null, key = null;
for(var i=0; i<objArr.length; i++) {
item=objArr[i];
key = Object.keys(item)[0];
item=item[key];

if(!result[key]){
result[key] = item;
}else{
result[key] += item;}
}a









share|improve this question























  • Why are you doing key = Object.keys(item)[0]; item=item[key]; ? You already know the name is key, so just do item.key or objArr[i].key. Also, using the [0] index won't necessarily always give you the same property.

    – user2736012
    Oct 7 '13 at 19:50
















10












10








10


5






How would one take a javascript array of objects such as:



my objArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:42},
{key:Mon Sep 24 2013 00:00:00 GMT-0400, val:78},
{key:Mon Sep 25 2013 00:00:00 GMT-0400, val:23},
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:54}]


and merge duplicate keys by summing the values.
In order to get something like this:



my reducedObjArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:96},
{key:Mon Sep 24 2013 00:00:00 GMT-0400, val:78},
{key:Mon Sep 25 2013 00:00:00 GMT-0400, val:23}]


I have tried iterating and adding to a new array, but this didn't work:



var reducedObjArr = ;
var item = null, key = null;
for(var i=0; i<objArr.length; i++) {
item=objArr[i];
key = Object.keys(item)[0];
item=item[key];

if(!result[key]){
result[key] = item;
}else{
result[key] += item;}
}a









share|improve this question














How would one take a javascript array of objects such as:



my objArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:42},
{key:Mon Sep 24 2013 00:00:00 GMT-0400, val:78},
{key:Mon Sep 25 2013 00:00:00 GMT-0400, val:23},
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:54}]


and merge duplicate keys by summing the values.
In order to get something like this:



my reducedObjArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:96},
{key:Mon Sep 24 2013 00:00:00 GMT-0400, val:78},
{key:Mon Sep 25 2013 00:00:00 GMT-0400, val:23}]


I have tried iterating and adding to a new array, but this didn't work:



var reducedObjArr = ;
var item = null, key = null;
for(var i=0; i<objArr.length; i++) {
item=objArr[i];
key = Object.keys(item)[0];
item=item[key];

if(!result[key]){
result[key] = item;
}else{
result[key] += item;}
}a






javascript arrays json object reduce






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Oct 7 '13 at 19:45









AlecPerkeyAlecPerkey

189719




189719













  • Why are you doing key = Object.keys(item)[0]; item=item[key]; ? You already know the name is key, so just do item.key or objArr[i].key. Also, using the [0] index won't necessarily always give you the same property.

    – user2736012
    Oct 7 '13 at 19:50





















  • Why are you doing key = Object.keys(item)[0]; item=item[key]; ? You already know the name is key, so just do item.key or objArr[i].key. Also, using the [0] index won't necessarily always give you the same property.

    – user2736012
    Oct 7 '13 at 19:50



















Why are you doing key = Object.keys(item)[0]; item=item[key]; ? You already know the name is key, so just do item.key or objArr[i].key. Also, using the [0] index won't necessarily always give you the same property.

– user2736012
Oct 7 '13 at 19:50







Why are you doing key = Object.keys(item)[0]; item=item[key]; ? You already know the name is key, so just do item.key or objArr[i].key. Also, using the [0] index won't necessarily always give you the same property.

– user2736012
Oct 7 '13 at 19:50














6 Answers
6






active

oldest

votes


















10














You should be assigning each object not found to the result with its .key property.



If it is found, then you need to add its .val.



var temp = {};
var obj = null;
for(var i=0; i < objArr.length; i++) {
obj=objArr[i];

if(!temp[obj.key]) {
temp[obj.key] = obj;
} else {
temp[obj.key].val += obj.val;
}
}
var result = ;
for (var prop in temp)
result.push(temp[prop]);




Also, part of the problem was that you were reusing the item variable to reference the value of .key, so you lost reference to the object.






share|improve this answer

































    5














    Rather than using a for loop and pushing values, you can directly use map and reduce:






    let objArr = [
    {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42},
    {key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78},
    {key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23},
    {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}
    ];

    // first, convert data into a Map with reduce
    let counts = objArr.reduce((prev, curr) => {
    let count = prev.get(curr.key) || 0;
    prev.set(curr.key, curr.val + count);
    return prev;
    }, new Map());

    // then, map your counts object back to an array
    let reducedObjArr = [...counts].map(([key, value]) => {
    return {key, value}
    })

    console.log(reducedObjArr);








    share|improve this answer

































      4














      You could use a hash table for the grouping by key.






      var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}],
      grouped = ;

      array.forEach(function (o) {
      if (!this[o.key]) {
      this[o.key] = { key: o.key, val: 0 };
      grouped.push(this[o.key]);
      }
      this[o.key].val += o.val;
      }, Object.create(null));

      console.log(grouped);

      .as-console-wrapper { max-height: 100% !important; top: 0; }





      Another approach is to collect all key/value pairs in a Map and format the final array with Array.from and a callback for the objects.






      var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54 }],
      grouped = Array.from(
      array.reduce((m, { key, val }) => m.set(key, (m.get(key) || 0) + val), new Map),
      ([key, val]) => ({ key, val })
      );

      console.log(grouped);

      .as-console-wrapper { max-height: 100% !important; top: 0; }








      share|improve this answer


























      • how to add multiple keys?

        – klent
        Aug 20 '18 at 2:55











      • @klent, replace val in this[o.key].val += o.val; with your property to add.

        – Nina Scholz
        Aug 20 '18 at 8:30











      • Sorry, I've meant how to add another condition before it adds for example if their's another property called 'category'. I want to check key and category.

        – klent
        Aug 20 '18 at 8:40






      • 1





        take an array for the keys to group, like groups = ['foo', 'bar'], inside the forEach use var key = groups.map(k => o[k]).join('|'); and then use this[key] instead of this[o.key]. maybe omit this at all and use a global variable for the object for grouping.

        – Nina Scholz
        Aug 20 '18 at 8:46











      • how to sum same values in object if my obj something like this obj = [ { menu: "apple", amount: 3}, { menu: "apple", amount: 1}, {menu: "melon", amount: 10}, {menu: "stawberry", amount: 7} ]; i want the ouput is [ {menu: apple, total: 4}, {menu: melon, total: 10}, and.......... ] @NinaScholz

        – Zum Dummi
        Jan 15 at 9:01



















      3














      var targetObj = {};
      for (var i = 0; i < objArr.length; i++) {
      if (!targetObj.hasOwnProperty(objArr[i].key)) {
      targetObj[objArr[i].key] = 0;
      }
      targetObj[objArr[i].key] += objArr[i].val;
      }


      http://jsfiddle.net/HUMxp/






      share|improve this answer
























      • OP wants the same key/value pairs, but with the val consolidated.

        – user2736012
        Oct 7 '13 at 20:11



















      0














      Here is an alternative for you, but similar to that of Explosion Pills, reuses the original array rather than creating a new one or a different object. The sort may not be necessary and will slow things down a little, but it could be removed.



      Javascript



      function reduceMyObjArr(arr) {
      var temp = {},
      index;

      for (index = arr.length - 1; index >= 0; index -= 1) {
      key = arr[index].key;
      if (temp.hasOwnProperty(key)) {
      arr[temp[key]].val += arr[index].val;
      arr.splice(index, 1);
      } else {
      temp[key] = index;
      }
      }

      arr.sort(function (a, b) {
      if (a.key === b.key) {
      return 0;
      }

      if (a.key < b.key) {
      return -1;
      }

      return 1;
      });

      return arr;
      }

      var myObjArr = [{
      key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
      val: 42
      }, {
      key: "Mon Sep 24 2013 00: 00: 00 GMT - 0400",
      val: 78
      }, {
      key: "Mon Sep 25 2013 00: 00: 00 GMT - 0400",
      val: 23
      }, {
      key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
      val: 54
      }];

      reduceMyObjArr(myObjArr);

      console.log(myObjArr);


      jsFiddle



      And a jsperf that compares this (with and without the sort) against the accepted answer. You can improve the performance test by extending the data set.






      share|improve this answer

































        0














        you can also try using javascript linq framework which is exactly same as sql statement which is given desired output with less written code and effective and found at linq.js






        var objArr = 
        [
        {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:42},
        {key:'Mon Sep 24 2013 00:00:00 GMT-0400', val:78},
        {key:'Mon Sep 25 2013 00:00:00 GMT-0400', val:23},
        {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:54}
        ];


        var aggregatedObject = Enumerable.From(objArr)
        .GroupBy("$.key", null,
        function (key, g) {
        return {
        key: key,
        contributions: g.Sum("$.val")
        }
        })
        .ToArray();

        console.log(aggregatedObject);

        <script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>





        which is pretty easy as compare to looping.
        i hope this may help.






        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f19233283%2fsum-javascript-object-propertya-values-with-same-object-propertyb-in-array-of-ob%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          6 Answers
          6






          active

          oldest

          votes








          6 Answers
          6






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          10














          You should be assigning each object not found to the result with its .key property.



          If it is found, then you need to add its .val.



          var temp = {};
          var obj = null;
          for(var i=0; i < objArr.length; i++) {
          obj=objArr[i];

          if(!temp[obj.key]) {
          temp[obj.key] = obj;
          } else {
          temp[obj.key].val += obj.val;
          }
          }
          var result = ;
          for (var prop in temp)
          result.push(temp[prop]);




          Also, part of the problem was that you were reusing the item variable to reference the value of .key, so you lost reference to the object.






          share|improve this answer






























            10














            You should be assigning each object not found to the result with its .key property.



            If it is found, then you need to add its .val.



            var temp = {};
            var obj = null;
            for(var i=0; i < objArr.length; i++) {
            obj=objArr[i];

            if(!temp[obj.key]) {
            temp[obj.key] = obj;
            } else {
            temp[obj.key].val += obj.val;
            }
            }
            var result = ;
            for (var prop in temp)
            result.push(temp[prop]);




            Also, part of the problem was that you were reusing the item variable to reference the value of .key, so you lost reference to the object.






            share|improve this answer




























              10












              10








              10







              You should be assigning each object not found to the result with its .key property.



              If it is found, then you need to add its .val.



              var temp = {};
              var obj = null;
              for(var i=0; i < objArr.length; i++) {
              obj=objArr[i];

              if(!temp[obj.key]) {
              temp[obj.key] = obj;
              } else {
              temp[obj.key].val += obj.val;
              }
              }
              var result = ;
              for (var prop in temp)
              result.push(temp[prop]);




              Also, part of the problem was that you were reusing the item variable to reference the value of .key, so you lost reference to the object.






              share|improve this answer















              You should be assigning each object not found to the result with its .key property.



              If it is found, then you need to add its .val.



              var temp = {};
              var obj = null;
              for(var i=0; i < objArr.length; i++) {
              obj=objArr[i];

              if(!temp[obj.key]) {
              temp[obj.key] = obj;
              } else {
              temp[obj.key].val += obj.val;
              }
              }
              var result = ;
              for (var prop in temp)
              result.push(temp[prop]);




              Also, part of the problem was that you were reusing the item variable to reference the value of .key, so you lost reference to the object.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Oct 7 '13 at 20:13

























              answered Oct 7 '13 at 19:53









              user2736012user2736012

              3,380811




              3,380811

























                  5














                  Rather than using a for loop and pushing values, you can directly use map and reduce:






                  let objArr = [
                  {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42},
                  {key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78},
                  {key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23},
                  {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}
                  ];

                  // first, convert data into a Map with reduce
                  let counts = objArr.reduce((prev, curr) => {
                  let count = prev.get(curr.key) || 0;
                  prev.set(curr.key, curr.val + count);
                  return prev;
                  }, new Map());

                  // then, map your counts object back to an array
                  let reducedObjArr = [...counts].map(([key, value]) => {
                  return {key, value}
                  })

                  console.log(reducedObjArr);








                  share|improve this answer






























                    5














                    Rather than using a for loop and pushing values, you can directly use map and reduce:






                    let objArr = [
                    {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42},
                    {key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78},
                    {key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23},
                    {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}
                    ];

                    // first, convert data into a Map with reduce
                    let counts = objArr.reduce((prev, curr) => {
                    let count = prev.get(curr.key) || 0;
                    prev.set(curr.key, curr.val + count);
                    return prev;
                    }, new Map());

                    // then, map your counts object back to an array
                    let reducedObjArr = [...counts].map(([key, value]) => {
                    return {key, value}
                    })

                    console.log(reducedObjArr);








                    share|improve this answer




























                      5












                      5








                      5







                      Rather than using a for loop and pushing values, you can directly use map and reduce:






                      let objArr = [
                      {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42},
                      {key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78},
                      {key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23},
                      {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}
                      ];

                      // first, convert data into a Map with reduce
                      let counts = objArr.reduce((prev, curr) => {
                      let count = prev.get(curr.key) || 0;
                      prev.set(curr.key, curr.val + count);
                      return prev;
                      }, new Map());

                      // then, map your counts object back to an array
                      let reducedObjArr = [...counts].map(([key, value]) => {
                      return {key, value}
                      })

                      console.log(reducedObjArr);








                      share|improve this answer















                      Rather than using a for loop and pushing values, you can directly use map and reduce:






                      let objArr = [
                      {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42},
                      {key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78},
                      {key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23},
                      {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}
                      ];

                      // first, convert data into a Map with reduce
                      let counts = objArr.reduce((prev, curr) => {
                      let count = prev.get(curr.key) || 0;
                      prev.set(curr.key, curr.val + count);
                      return prev;
                      }, new Map());

                      // then, map your counts object back to an array
                      let reducedObjArr = [...counts].map(([key, value]) => {
                      return {key, value}
                      })

                      console.log(reducedObjArr);








                      let objArr = [
                      {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42},
                      {key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78},
                      {key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23},
                      {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}
                      ];

                      // first, convert data into a Map with reduce
                      let counts = objArr.reduce((prev, curr) => {
                      let count = prev.get(curr.key) || 0;
                      prev.set(curr.key, curr.val + count);
                      return prev;
                      }, new Map());

                      // then, map your counts object back to an array
                      let reducedObjArr = [...counts].map(([key, value]) => {
                      return {key, value}
                      })

                      console.log(reducedObjArr);





                      let objArr = [
                      {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42},
                      {key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78},
                      {key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23},
                      {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}
                      ];

                      // first, convert data into a Map with reduce
                      let counts = objArr.reduce((prev, curr) => {
                      let count = prev.get(curr.key) || 0;
                      prev.set(curr.key, curr.val + count);
                      return prev;
                      }, new Map());

                      // then, map your counts object back to an array
                      let reducedObjArr = [...counts].map(([key, value]) => {
                      return {key, value}
                      })

                      console.log(reducedObjArr);






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jun 3 '16 at 21:20

























                      answered Jun 3 '16 at 21:15









                      HammsHamms

                      3,5511221




                      3,5511221























                          4














                          You could use a hash table for the grouping by key.






                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}],
                          grouped = ;

                          array.forEach(function (o) {
                          if (!this[o.key]) {
                          this[o.key] = { key: o.key, val: 0 };
                          grouped.push(this[o.key]);
                          }
                          this[o.key].val += o.val;
                          }, Object.create(null));

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }





                          Another approach is to collect all key/value pairs in a Map and format the final array with Array.from and a callback for the objects.






                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54 }],
                          grouped = Array.from(
                          array.reduce((m, { key, val }) => m.set(key, (m.get(key) || 0) + val), new Map),
                          ([key, val]) => ({ key, val })
                          );

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }








                          share|improve this answer


























                          • how to add multiple keys?

                            – klent
                            Aug 20 '18 at 2:55











                          • @klent, replace val in this[o.key].val += o.val; with your property to add.

                            – Nina Scholz
                            Aug 20 '18 at 8:30











                          • Sorry, I've meant how to add another condition before it adds for example if their's another property called 'category'. I want to check key and category.

                            – klent
                            Aug 20 '18 at 8:40






                          • 1





                            take an array for the keys to group, like groups = ['foo', 'bar'], inside the forEach use var key = groups.map(k => o[k]).join('|'); and then use this[key] instead of this[o.key]. maybe omit this at all and use a global variable for the object for grouping.

                            – Nina Scholz
                            Aug 20 '18 at 8:46











                          • how to sum same values in object if my obj something like this obj = [ { menu: "apple", amount: 3}, { menu: "apple", amount: 1}, {menu: "melon", amount: 10}, {menu: "stawberry", amount: 7} ]; i want the ouput is [ {menu: apple, total: 4}, {menu: melon, total: 10}, and.......... ] @NinaScholz

                            – Zum Dummi
                            Jan 15 at 9:01
















                          4














                          You could use a hash table for the grouping by key.






                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}],
                          grouped = ;

                          array.forEach(function (o) {
                          if (!this[o.key]) {
                          this[o.key] = { key: o.key, val: 0 };
                          grouped.push(this[o.key]);
                          }
                          this[o.key].val += o.val;
                          }, Object.create(null));

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }





                          Another approach is to collect all key/value pairs in a Map and format the final array with Array.from and a callback for the objects.






                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54 }],
                          grouped = Array.from(
                          array.reduce((m, { key, val }) => m.set(key, (m.get(key) || 0) + val), new Map),
                          ([key, val]) => ({ key, val })
                          );

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }








                          share|improve this answer


























                          • how to add multiple keys?

                            – klent
                            Aug 20 '18 at 2:55











                          • @klent, replace val in this[o.key].val += o.val; with your property to add.

                            – Nina Scholz
                            Aug 20 '18 at 8:30











                          • Sorry, I've meant how to add another condition before it adds for example if their's another property called 'category'. I want to check key and category.

                            – klent
                            Aug 20 '18 at 8:40






                          • 1





                            take an array for the keys to group, like groups = ['foo', 'bar'], inside the forEach use var key = groups.map(k => o[k]).join('|'); and then use this[key] instead of this[o.key]. maybe omit this at all and use a global variable for the object for grouping.

                            – Nina Scholz
                            Aug 20 '18 at 8:46











                          • how to sum same values in object if my obj something like this obj = [ { menu: "apple", amount: 3}, { menu: "apple", amount: 1}, {menu: "melon", amount: 10}, {menu: "stawberry", amount: 7} ]; i want the ouput is [ {menu: apple, total: 4}, {menu: melon, total: 10}, and.......... ] @NinaScholz

                            – Zum Dummi
                            Jan 15 at 9:01














                          4












                          4








                          4







                          You could use a hash table for the grouping by key.






                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}],
                          grouped = ;

                          array.forEach(function (o) {
                          if (!this[o.key]) {
                          this[o.key] = { key: o.key, val: 0 };
                          grouped.push(this[o.key]);
                          }
                          this[o.key].val += o.val;
                          }, Object.create(null));

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }





                          Another approach is to collect all key/value pairs in a Map and format the final array with Array.from and a callback for the objects.






                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54 }],
                          grouped = Array.from(
                          array.reduce((m, { key, val }) => m.set(key, (m.get(key) || 0) + val), new Map),
                          ([key, val]) => ({ key, val })
                          );

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }








                          share|improve this answer















                          You could use a hash table for the grouping by key.






                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}],
                          grouped = ;

                          array.forEach(function (o) {
                          if (!this[o.key]) {
                          this[o.key] = { key: o.key, val: 0 };
                          grouped.push(this[o.key]);
                          }
                          this[o.key].val += o.val;
                          }, Object.create(null));

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }





                          Another approach is to collect all key/value pairs in a Map and format the final array with Array.from and a callback for the objects.






                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54 }],
                          grouped = Array.from(
                          array.reduce((m, { key, val }) => m.set(key, (m.get(key) || 0) + val), new Map),
                          ([key, val]) => ({ key, val })
                          );

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }








                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}],
                          grouped = ;

                          array.forEach(function (o) {
                          if (!this[o.key]) {
                          this[o.key] = { key: o.key, val: 0 };
                          grouped.push(this[o.key]);
                          }
                          this[o.key].val += o.val;
                          }, Object.create(null));

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }





                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}],
                          grouped = ;

                          array.forEach(function (o) {
                          if (!this[o.key]) {
                          this[o.key] = { key: o.key, val: 0 };
                          grouped.push(this[o.key]);
                          }
                          this[o.key].val += o.val;
                          }, Object.create(null));

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }





                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54 }],
                          grouped = Array.from(
                          array.reduce((m, { key, val }) => m.set(key, (m.get(key) || 0) + val), new Map),
                          ([key, val]) => ({ key, val })
                          );

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }





                          var array = [{ key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42 }, { key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78 }, { key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23 }, { key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54 }],
                          grouped = Array.from(
                          array.reduce((m, { key, val }) => m.set(key, (m.get(key) || 0) + val), new Map),
                          ([key, val]) => ({ key, val })
                          );

                          console.log(grouped);

                          .as-console-wrapper { max-height: 100% !important; top: 0; }






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Feb 5 at 7:31

























                          answered Jan 13 '17 at 19:39









                          Nina ScholzNina Scholz

                          193k15104177




                          193k15104177













                          • how to add multiple keys?

                            – klent
                            Aug 20 '18 at 2:55











                          • @klent, replace val in this[o.key].val += o.val; with your property to add.

                            – Nina Scholz
                            Aug 20 '18 at 8:30











                          • Sorry, I've meant how to add another condition before it adds for example if their's another property called 'category'. I want to check key and category.

                            – klent
                            Aug 20 '18 at 8:40






                          • 1





                            take an array for the keys to group, like groups = ['foo', 'bar'], inside the forEach use var key = groups.map(k => o[k]).join('|'); and then use this[key] instead of this[o.key]. maybe omit this at all and use a global variable for the object for grouping.

                            – Nina Scholz
                            Aug 20 '18 at 8:46











                          • how to sum same values in object if my obj something like this obj = [ { menu: "apple", amount: 3}, { menu: "apple", amount: 1}, {menu: "melon", amount: 10}, {menu: "stawberry", amount: 7} ]; i want the ouput is [ {menu: apple, total: 4}, {menu: melon, total: 10}, and.......... ] @NinaScholz

                            – Zum Dummi
                            Jan 15 at 9:01



















                          • how to add multiple keys?

                            – klent
                            Aug 20 '18 at 2:55











                          • @klent, replace val in this[o.key].val += o.val; with your property to add.

                            – Nina Scholz
                            Aug 20 '18 at 8:30











                          • Sorry, I've meant how to add another condition before it adds for example if their's another property called 'category'. I want to check key and category.

                            – klent
                            Aug 20 '18 at 8:40






                          • 1





                            take an array for the keys to group, like groups = ['foo', 'bar'], inside the forEach use var key = groups.map(k => o[k]).join('|'); and then use this[key] instead of this[o.key]. maybe omit this at all and use a global variable for the object for grouping.

                            – Nina Scholz
                            Aug 20 '18 at 8:46











                          • how to sum same values in object if my obj something like this obj = [ { menu: "apple", amount: 3}, { menu: "apple", amount: 1}, {menu: "melon", amount: 10}, {menu: "stawberry", amount: 7} ]; i want the ouput is [ {menu: apple, total: 4}, {menu: melon, total: 10}, and.......... ] @NinaScholz

                            – Zum Dummi
                            Jan 15 at 9:01

















                          how to add multiple keys?

                          – klent
                          Aug 20 '18 at 2:55





                          how to add multiple keys?

                          – klent
                          Aug 20 '18 at 2:55













                          @klent, replace val in this[o.key].val += o.val; with your property to add.

                          – Nina Scholz
                          Aug 20 '18 at 8:30





                          @klent, replace val in this[o.key].val += o.val; with your property to add.

                          – Nina Scholz
                          Aug 20 '18 at 8:30













                          Sorry, I've meant how to add another condition before it adds for example if their's another property called 'category'. I want to check key and category.

                          – klent
                          Aug 20 '18 at 8:40





                          Sorry, I've meant how to add another condition before it adds for example if their's another property called 'category'. I want to check key and category.

                          – klent
                          Aug 20 '18 at 8:40




                          1




                          1





                          take an array for the keys to group, like groups = ['foo', 'bar'], inside the forEach use var key = groups.map(k => o[k]).join('|'); and then use this[key] instead of this[o.key]. maybe omit this at all and use a global variable for the object for grouping.

                          – Nina Scholz
                          Aug 20 '18 at 8:46





                          take an array for the keys to group, like groups = ['foo', 'bar'], inside the forEach use var key = groups.map(k => o[k]).join('|'); and then use this[key] instead of this[o.key]. maybe omit this at all and use a global variable for the object for grouping.

                          – Nina Scholz
                          Aug 20 '18 at 8:46













                          how to sum same values in object if my obj something like this obj = [ { menu: "apple", amount: 3}, { menu: "apple", amount: 1}, {menu: "melon", amount: 10}, {menu: "stawberry", amount: 7} ]; i want the ouput is [ {menu: apple, total: 4}, {menu: melon, total: 10}, and.......... ] @NinaScholz

                          – Zum Dummi
                          Jan 15 at 9:01





                          how to sum same values in object if my obj something like this obj = [ { menu: "apple", amount: 3}, { menu: "apple", amount: 1}, {menu: "melon", amount: 10}, {menu: "stawberry", amount: 7} ]; i want the ouput is [ {menu: apple, total: 4}, {menu: melon, total: 10}, and.......... ] @NinaScholz

                          – Zum Dummi
                          Jan 15 at 9:01











                          3














                          var targetObj = {};
                          for (var i = 0; i < objArr.length; i++) {
                          if (!targetObj.hasOwnProperty(objArr[i].key)) {
                          targetObj[objArr[i].key] = 0;
                          }
                          targetObj[objArr[i].key] += objArr[i].val;
                          }


                          http://jsfiddle.net/HUMxp/






                          share|improve this answer
























                          • OP wants the same key/value pairs, but with the val consolidated.

                            – user2736012
                            Oct 7 '13 at 20:11
















                          3














                          var targetObj = {};
                          for (var i = 0; i < objArr.length; i++) {
                          if (!targetObj.hasOwnProperty(objArr[i].key)) {
                          targetObj[objArr[i].key] = 0;
                          }
                          targetObj[objArr[i].key] += objArr[i].val;
                          }


                          http://jsfiddle.net/HUMxp/






                          share|improve this answer
























                          • OP wants the same key/value pairs, but with the val consolidated.

                            – user2736012
                            Oct 7 '13 at 20:11














                          3












                          3








                          3







                          var targetObj = {};
                          for (var i = 0; i < objArr.length; i++) {
                          if (!targetObj.hasOwnProperty(objArr[i].key)) {
                          targetObj[objArr[i].key] = 0;
                          }
                          targetObj[objArr[i].key] += objArr[i].val;
                          }


                          http://jsfiddle.net/HUMxp/






                          share|improve this answer













                          var targetObj = {};
                          for (var i = 0; i < objArr.length; i++) {
                          if (!targetObj.hasOwnProperty(objArr[i].key)) {
                          targetObj[objArr[i].key] = 0;
                          }
                          targetObj[objArr[i].key] += objArr[i].val;
                          }


                          http://jsfiddle.net/HUMxp/







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Oct 7 '13 at 19:53









                          Explosion PillsExplosion Pills

                          151k38228317




                          151k38228317













                          • OP wants the same key/value pairs, but with the val consolidated.

                            – user2736012
                            Oct 7 '13 at 20:11



















                          • OP wants the same key/value pairs, but with the val consolidated.

                            – user2736012
                            Oct 7 '13 at 20:11

















                          OP wants the same key/value pairs, but with the val consolidated.

                          – user2736012
                          Oct 7 '13 at 20:11





                          OP wants the same key/value pairs, but with the val consolidated.

                          – user2736012
                          Oct 7 '13 at 20:11











                          0














                          Here is an alternative for you, but similar to that of Explosion Pills, reuses the original array rather than creating a new one or a different object. The sort may not be necessary and will slow things down a little, but it could be removed.



                          Javascript



                          function reduceMyObjArr(arr) {
                          var temp = {},
                          index;

                          for (index = arr.length - 1; index >= 0; index -= 1) {
                          key = arr[index].key;
                          if (temp.hasOwnProperty(key)) {
                          arr[temp[key]].val += arr[index].val;
                          arr.splice(index, 1);
                          } else {
                          temp[key] = index;
                          }
                          }

                          arr.sort(function (a, b) {
                          if (a.key === b.key) {
                          return 0;
                          }

                          if (a.key < b.key) {
                          return -1;
                          }

                          return 1;
                          });

                          return arr;
                          }

                          var myObjArr = [{
                          key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
                          val: 42
                          }, {
                          key: "Mon Sep 24 2013 00: 00: 00 GMT - 0400",
                          val: 78
                          }, {
                          key: "Mon Sep 25 2013 00: 00: 00 GMT - 0400",
                          val: 23
                          }, {
                          key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
                          val: 54
                          }];

                          reduceMyObjArr(myObjArr);

                          console.log(myObjArr);


                          jsFiddle



                          And a jsperf that compares this (with and without the sort) against the accepted answer. You can improve the performance test by extending the data set.






                          share|improve this answer






























                            0














                            Here is an alternative for you, but similar to that of Explosion Pills, reuses the original array rather than creating a new one or a different object. The sort may not be necessary and will slow things down a little, but it could be removed.



                            Javascript



                            function reduceMyObjArr(arr) {
                            var temp = {},
                            index;

                            for (index = arr.length - 1; index >= 0; index -= 1) {
                            key = arr[index].key;
                            if (temp.hasOwnProperty(key)) {
                            arr[temp[key]].val += arr[index].val;
                            arr.splice(index, 1);
                            } else {
                            temp[key] = index;
                            }
                            }

                            arr.sort(function (a, b) {
                            if (a.key === b.key) {
                            return 0;
                            }

                            if (a.key < b.key) {
                            return -1;
                            }

                            return 1;
                            });

                            return arr;
                            }

                            var myObjArr = [{
                            key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
                            val: 42
                            }, {
                            key: "Mon Sep 24 2013 00: 00: 00 GMT - 0400",
                            val: 78
                            }, {
                            key: "Mon Sep 25 2013 00: 00: 00 GMT - 0400",
                            val: 23
                            }, {
                            key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
                            val: 54
                            }];

                            reduceMyObjArr(myObjArr);

                            console.log(myObjArr);


                            jsFiddle



                            And a jsperf that compares this (with and without the sort) against the accepted answer. You can improve the performance test by extending the data set.






                            share|improve this answer




























                              0












                              0








                              0







                              Here is an alternative for you, but similar to that of Explosion Pills, reuses the original array rather than creating a new one or a different object. The sort may not be necessary and will slow things down a little, but it could be removed.



                              Javascript



                              function reduceMyObjArr(arr) {
                              var temp = {},
                              index;

                              for (index = arr.length - 1; index >= 0; index -= 1) {
                              key = arr[index].key;
                              if (temp.hasOwnProperty(key)) {
                              arr[temp[key]].val += arr[index].val;
                              arr.splice(index, 1);
                              } else {
                              temp[key] = index;
                              }
                              }

                              arr.sort(function (a, b) {
                              if (a.key === b.key) {
                              return 0;
                              }

                              if (a.key < b.key) {
                              return -1;
                              }

                              return 1;
                              });

                              return arr;
                              }

                              var myObjArr = [{
                              key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
                              val: 42
                              }, {
                              key: "Mon Sep 24 2013 00: 00: 00 GMT - 0400",
                              val: 78
                              }, {
                              key: "Mon Sep 25 2013 00: 00: 00 GMT - 0400",
                              val: 23
                              }, {
                              key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
                              val: 54
                              }];

                              reduceMyObjArr(myObjArr);

                              console.log(myObjArr);


                              jsFiddle



                              And a jsperf that compares this (with and without the sort) against the accepted answer. You can improve the performance test by extending the data set.






                              share|improve this answer















                              Here is an alternative for you, but similar to that of Explosion Pills, reuses the original array rather than creating a new one or a different object. The sort may not be necessary and will slow things down a little, but it could be removed.



                              Javascript



                              function reduceMyObjArr(arr) {
                              var temp = {},
                              index;

                              for (index = arr.length - 1; index >= 0; index -= 1) {
                              key = arr[index].key;
                              if (temp.hasOwnProperty(key)) {
                              arr[temp[key]].val += arr[index].val;
                              arr.splice(index, 1);
                              } else {
                              temp[key] = index;
                              }
                              }

                              arr.sort(function (a, b) {
                              if (a.key === b.key) {
                              return 0;
                              }

                              if (a.key < b.key) {
                              return -1;
                              }

                              return 1;
                              });

                              return arr;
                              }

                              var myObjArr = [{
                              key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
                              val: 42
                              }, {
                              key: "Mon Sep 24 2013 00: 00: 00 GMT - 0400",
                              val: 78
                              }, {
                              key: "Mon Sep 25 2013 00: 00: 00 GMT - 0400",
                              val: 23
                              }, {
                              key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
                              val: 54
                              }];

                              reduceMyObjArr(myObjArr);

                              console.log(myObjArr);


                              jsFiddle



                              And a jsperf that compares this (with and without the sort) against the accepted answer. You can improve the performance test by extending the data set.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited May 23 '17 at 11:33









                              Community

                              11




                              11










                              answered Oct 7 '13 at 21:00









                              Xotic750Xotic750

                              16.4k74165




                              16.4k74165























                                  0














                                  you can also try using javascript linq framework which is exactly same as sql statement which is given desired output with less written code and effective and found at linq.js






                                  var objArr = 
                                  [
                                  {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:42},
                                  {key:'Mon Sep 24 2013 00:00:00 GMT-0400', val:78},
                                  {key:'Mon Sep 25 2013 00:00:00 GMT-0400', val:23},
                                  {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:54}
                                  ];


                                  var aggregatedObject = Enumerable.From(objArr)
                                  .GroupBy("$.key", null,
                                  function (key, g) {
                                  return {
                                  key: key,
                                  contributions: g.Sum("$.val")
                                  }
                                  })
                                  .ToArray();

                                  console.log(aggregatedObject);

                                  <script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>





                                  which is pretty easy as compare to looping.
                                  i hope this may help.






                                  share|improve this answer




























                                    0














                                    you can also try using javascript linq framework which is exactly same as sql statement which is given desired output with less written code and effective and found at linq.js






                                    var objArr = 
                                    [
                                    {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:42},
                                    {key:'Mon Sep 24 2013 00:00:00 GMT-0400', val:78},
                                    {key:'Mon Sep 25 2013 00:00:00 GMT-0400', val:23},
                                    {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:54}
                                    ];


                                    var aggregatedObject = Enumerable.From(objArr)
                                    .GroupBy("$.key", null,
                                    function (key, g) {
                                    return {
                                    key: key,
                                    contributions: g.Sum("$.val")
                                    }
                                    })
                                    .ToArray();

                                    console.log(aggregatedObject);

                                    <script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>





                                    which is pretty easy as compare to looping.
                                    i hope this may help.






                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      you can also try using javascript linq framework which is exactly same as sql statement which is given desired output with less written code and effective and found at linq.js






                                      var objArr = 
                                      [
                                      {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:42},
                                      {key:'Mon Sep 24 2013 00:00:00 GMT-0400', val:78},
                                      {key:'Mon Sep 25 2013 00:00:00 GMT-0400', val:23},
                                      {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:54}
                                      ];


                                      var aggregatedObject = Enumerable.From(objArr)
                                      .GroupBy("$.key", null,
                                      function (key, g) {
                                      return {
                                      key: key,
                                      contributions: g.Sum("$.val")
                                      }
                                      })
                                      .ToArray();

                                      console.log(aggregatedObject);

                                      <script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>





                                      which is pretty easy as compare to looping.
                                      i hope this may help.






                                      share|improve this answer













                                      you can also try using javascript linq framework which is exactly same as sql statement which is given desired output with less written code and effective and found at linq.js






                                      var objArr = 
                                      [
                                      {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:42},
                                      {key:'Mon Sep 24 2013 00:00:00 GMT-0400', val:78},
                                      {key:'Mon Sep 25 2013 00:00:00 GMT-0400', val:23},
                                      {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:54}
                                      ];


                                      var aggregatedObject = Enumerable.From(objArr)
                                      .GroupBy("$.key", null,
                                      function (key, g) {
                                      return {
                                      key: key,
                                      contributions: g.Sum("$.val")
                                      }
                                      })
                                      .ToArray();

                                      console.log(aggregatedObject);

                                      <script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>





                                      which is pretty easy as compare to looping.
                                      i hope this may help.






                                      var objArr = 
                                      [
                                      {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:42},
                                      {key:'Mon Sep 24 2013 00:00:00 GMT-0400', val:78},
                                      {key:'Mon Sep 25 2013 00:00:00 GMT-0400', val:23},
                                      {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:54}
                                      ];


                                      var aggregatedObject = Enumerable.From(objArr)
                                      .GroupBy("$.key", null,
                                      function (key, g) {
                                      return {
                                      key: key,
                                      contributions: g.Sum("$.val")
                                      }
                                      })
                                      .ToArray();

                                      console.log(aggregatedObject);

                                      <script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>





                                      var objArr = 
                                      [
                                      {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:42},
                                      {key:'Mon Sep 24 2013 00:00:00 GMT-0400', val:78},
                                      {key:'Mon Sep 25 2013 00:00:00 GMT-0400', val:23},
                                      {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:54}
                                      ];


                                      var aggregatedObject = Enumerable.From(objArr)
                                      .GroupBy("$.key", null,
                                      function (key, g) {
                                      return {
                                      key: key,
                                      contributions: g.Sum("$.val")
                                      }
                                      })
                                      .ToArray();

                                      console.log(aggregatedObject);

                                      <script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jul 10 '16 at 18:32









                                      Sanjay RadadiyaSanjay Radadiya

                                      932820




                                      932820






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f19233283%2fsum-javascript-object-propertya-values-with-same-object-propertyb-in-array-of-ob%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          MongoDB - Not Authorized To Execute Command

                                          How to fix TextFormField cause rebuild widget in Flutter

                                          Npm cannot find a required file even through it is in the searched directory