How to get the minimum and maximum date and grouped it by id












-2















I have this array of data



[{"id":1, "start":"2018-10-10", "end":"2018-11-10"},
{"id":1, "start":"2018-11-10", "end":"2018-12-10"},
{"id":2, "start":"2018-11-22", "end":"2018-11-30"}]


I wanted to get the minimum in the start and the maximum in the end.



My desired output would be



{"id":1, "start":"2018-10-10", "end":"2018-12-10"},
{"id":2, "start":"2018-11-22", "end":"2018-11-30"}


I tried doing like this:



data.sort((a,b) => a.start.toString().localeCompare(b.start))









share|improve this question

























  • There is zero jQuery in your question. Also, none of the objects have a start_date property, and you don't have to call toString() on something that's already a string.

    – CertainPerformance
    Nov 20 '18 at 8:28













  • I thought sort is jquery sorry

    – sad saddest
    Nov 20 '18 at 8:28











  • why haven't you used any of the grouping code you got in the question you asked 2 hours ago? Stackoverflow is not a free code writing service. People will happily help but we aren't here to do all the work for you

    – charlietfl
    Nov 20 '18 at 8:37


















-2















I have this array of data



[{"id":1, "start":"2018-10-10", "end":"2018-11-10"},
{"id":1, "start":"2018-11-10", "end":"2018-12-10"},
{"id":2, "start":"2018-11-22", "end":"2018-11-30"}]


I wanted to get the minimum in the start and the maximum in the end.



My desired output would be



{"id":1, "start":"2018-10-10", "end":"2018-12-10"},
{"id":2, "start":"2018-11-22", "end":"2018-11-30"}


I tried doing like this:



data.sort((a,b) => a.start.toString().localeCompare(b.start))









share|improve this question

























  • There is zero jQuery in your question. Also, none of the objects have a start_date property, and you don't have to call toString() on something that's already a string.

    – CertainPerformance
    Nov 20 '18 at 8:28













  • I thought sort is jquery sorry

    – sad saddest
    Nov 20 '18 at 8:28











  • why haven't you used any of the grouping code you got in the question you asked 2 hours ago? Stackoverflow is not a free code writing service. People will happily help but we aren't here to do all the work for you

    – charlietfl
    Nov 20 '18 at 8:37
















-2












-2








-2


1






I have this array of data



[{"id":1, "start":"2018-10-10", "end":"2018-11-10"},
{"id":1, "start":"2018-11-10", "end":"2018-12-10"},
{"id":2, "start":"2018-11-22", "end":"2018-11-30"}]


I wanted to get the minimum in the start and the maximum in the end.



My desired output would be



{"id":1, "start":"2018-10-10", "end":"2018-12-10"},
{"id":2, "start":"2018-11-22", "end":"2018-11-30"}


I tried doing like this:



data.sort((a,b) => a.start.toString().localeCompare(b.start))









share|improve this question
















I have this array of data



[{"id":1, "start":"2018-10-10", "end":"2018-11-10"},
{"id":1, "start":"2018-11-10", "end":"2018-12-10"},
{"id":2, "start":"2018-11-22", "end":"2018-11-30"}]


I wanted to get the minimum in the start and the maximum in the end.



My desired output would be



{"id":1, "start":"2018-10-10", "end":"2018-12-10"},
{"id":2, "start":"2018-11-22", "end":"2018-11-30"}


I tried doing like this:



data.sort((a,b) => a.start.toString().localeCompare(b.start))






javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 8:46









HMR

13.9k113899




13.9k113899










asked Nov 20 '18 at 8:27









sad saddestsad saddest

338




338













  • There is zero jQuery in your question. Also, none of the objects have a start_date property, and you don't have to call toString() on something that's already a string.

    – CertainPerformance
    Nov 20 '18 at 8:28













  • I thought sort is jquery sorry

    – sad saddest
    Nov 20 '18 at 8:28











  • why haven't you used any of the grouping code you got in the question you asked 2 hours ago? Stackoverflow is not a free code writing service. People will happily help but we aren't here to do all the work for you

    – charlietfl
    Nov 20 '18 at 8:37





















  • There is zero jQuery in your question. Also, none of the objects have a start_date property, and you don't have to call toString() on something that's already a string.

    – CertainPerformance
    Nov 20 '18 at 8:28













  • I thought sort is jquery sorry

    – sad saddest
    Nov 20 '18 at 8:28











  • why haven't you used any of the grouping code you got in the question you asked 2 hours ago? Stackoverflow is not a free code writing service. People will happily help but we aren't here to do all the work for you

    – charlietfl
    Nov 20 '18 at 8:37



















There is zero jQuery in your question. Also, none of the objects have a start_date property, and you don't have to call toString() on something that's already a string.

– CertainPerformance
Nov 20 '18 at 8:28







There is zero jQuery in your question. Also, none of the objects have a start_date property, and you don't have to call toString() on something that's already a string.

– CertainPerformance
Nov 20 '18 at 8:28















I thought sort is jquery sorry

– sad saddest
Nov 20 '18 at 8:28





I thought sort is jquery sorry

– sad saddest
Nov 20 '18 at 8:28













why haven't you used any of the grouping code you got in the question you asked 2 hours ago? Stackoverflow is not a free code writing service. People will happily help but we aren't here to do all the work for you

– charlietfl
Nov 20 '18 at 8:37







why haven't you used any of the grouping code you got in the question you asked 2 hours ago? Stackoverflow is not a free code writing service. People will happily help but we aren't here to do all the work for you

– charlietfl
Nov 20 '18 at 8:37














4 Answers
4






active

oldest

votes


















1














What you are trying to do will require a custom solution where you merge two entries. In the below function I have iterated your array in chunks of same id first I have sorted it based on id and kept a min and max of the index where your logic says on date






function groupById(arr){
arr.sort((a,b)=>a.id-b.id);
let arrNew = ;
let min=0, max=0, currentid = arr[0].id;
for(i=1; i<arr.length+1;i++){
if(!arr[i] || arr[i].id!=currentid){
arrNew.push({id:currentid, start:arr[min].start, end: arr[max].end});
min = i;max=i;currentid=(arr[i]||{}).id;
}
if(!arr[i]){
break;
}
if(arr[i].start<arr[min].start){
min = i;
}
if(arr[i].end>arr[max].end){
max = i;
}
}
return arrNew;
}

var result = groupById([
{"id":1, "start":"2018-10-10", "end":"2018-11-10"},
{"id":1, "start":"2018-11-10", "end":"2018-12-10"},
{"id":2, "start":"2018-11-22", "end":"2018-11-30"}
]);

console.log(result);








share|improve this answer































    0














    you need to sort array using date comparison and also reduce it by id.



    var data = [{
    "id": 1,
    "start": "2018-10-10",
    "end": "2018-11-10"
    },
    {
    "id": 1,
    "start": "2018-11-10",
    "end": "2018-12-10"
    },
    {
    "id": 2,
    "start": "2018-11-22",
    "end": "2018-11-30"
    }
    ];


    let result = data.sort((a, b) => new Date(a.start) > new Date(b.start)).reduce(function(r, a) {
    if (!r[a.id] || r[a.id][0].id !== a.id) {
    r[a.id] = r[a.id] || ;
    r[a.id].push(a);
    }

    return r;
    }, Object.create(null));

    console.log(result)





    share|improve this answer































      0














      You seem to be having multiple things that need to be grouped and reduces (as shown by comment referring to other question). So I will provide some general methods in this answer.



      MDN has excelent documentation on all methods used here like map, reduce and Object.value, I would advice you have a look there to understand the code better.



      ES6 syntax is explained very well here






      const data = [
      { id: 1, start: '2018-10-10', end: '2018-11-10' },
      { id: 1, start: '2018-11-10', end: '2018-12-10' },
      { id: 2, start: '2018-11-22', end: '2018-11-30' },
      ];

      const groupBy = (arr, key) =>
      arr.reduce(
      (result, item) => (
      result[item[key]].push(item), result
      ),
      arr.reduce(
      (result, item) => ((result[item[key]] = ), result),
      {},
      ),
      );
      const returnLowHigh = (comp) => (a, b) =>
      a.localeCompare(b) === comp ? a : b;
      const lowest = returnLowHigh(-1);
      const highest = returnLowHigh(1);
      console.log(
      Object.values(groupBy(data, 'id')).map((items) =>
      items.reduce((result, { id, start, end }) => ({
      id,
      start: lowest(result.start, start),
      end: highest(result.end, end),
      })),
      ),
      );








      share|improve this answer































        0














        You can use reduce function and check the start and end date and if start date






        let old = [{
        "id": 1,
        "start": "2018-10-10",
        "end": "2018-11-10"
        },
        {
        "id": 1,
        "start": "2018-11-10",
        "end": "2018-12-10"
        },
        {
        "id": 2,
        "start": "2018-11-22",
        "end": "2018-11-30"
        }
        ];

        let k = old.reduce(function(acc, curr) {
        let findId = acc.findIndex((item) => {
        return item.id === curr.id
        });

        if (findId === -1) {
        acc.push(curr)
        } else {
        let oldStartDate = createDate(acc[findId].start);
        let newStartDate = createDate(curr.start);
        let oldEndDate = createDate(acc[findId].end);
        let newEndDate = createDate(curr.end);


        if (newStartDate < oldStartDate) {

        acc[findId].start = curr.start
        }
        if (newEndDate > oldEndDate) {

        acc[findId].end = curr.end
        }

        }

        return acc;

        }, );

        console.log(k);

        function createDate(dte) {
        let dt = new Date(dte);
        return `${dt.getYear()}-${dt.getMonth()}-${dt.getDate()}`

        }








        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%2f53388901%2fhow-to-get-the-minimum-and-maximum-date-and-grouped-it-by-id%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          What you are trying to do will require a custom solution where you merge two entries. In the below function I have iterated your array in chunks of same id first I have sorted it based on id and kept a min and max of the index where your logic says on date






          function groupById(arr){
          arr.sort((a,b)=>a.id-b.id);
          let arrNew = ;
          let min=0, max=0, currentid = arr[0].id;
          for(i=1; i<arr.length+1;i++){
          if(!arr[i] || arr[i].id!=currentid){
          arrNew.push({id:currentid, start:arr[min].start, end: arr[max].end});
          min = i;max=i;currentid=(arr[i]||{}).id;
          }
          if(!arr[i]){
          break;
          }
          if(arr[i].start<arr[min].start){
          min = i;
          }
          if(arr[i].end>arr[max].end){
          max = i;
          }
          }
          return arrNew;
          }

          var result = groupById([
          {"id":1, "start":"2018-10-10", "end":"2018-11-10"},
          {"id":1, "start":"2018-11-10", "end":"2018-12-10"},
          {"id":2, "start":"2018-11-22", "end":"2018-11-30"}
          ]);

          console.log(result);








          share|improve this answer




























            1














            What you are trying to do will require a custom solution where you merge two entries. In the below function I have iterated your array in chunks of same id first I have sorted it based on id and kept a min and max of the index where your logic says on date






            function groupById(arr){
            arr.sort((a,b)=>a.id-b.id);
            let arrNew = ;
            let min=0, max=0, currentid = arr[0].id;
            for(i=1; i<arr.length+1;i++){
            if(!arr[i] || arr[i].id!=currentid){
            arrNew.push({id:currentid, start:arr[min].start, end: arr[max].end});
            min = i;max=i;currentid=(arr[i]||{}).id;
            }
            if(!arr[i]){
            break;
            }
            if(arr[i].start<arr[min].start){
            min = i;
            }
            if(arr[i].end>arr[max].end){
            max = i;
            }
            }
            return arrNew;
            }

            var result = groupById([
            {"id":1, "start":"2018-10-10", "end":"2018-11-10"},
            {"id":1, "start":"2018-11-10", "end":"2018-12-10"},
            {"id":2, "start":"2018-11-22", "end":"2018-11-30"}
            ]);

            console.log(result);








            share|improve this answer


























              1












              1








              1







              What you are trying to do will require a custom solution where you merge two entries. In the below function I have iterated your array in chunks of same id first I have sorted it based on id and kept a min and max of the index where your logic says on date






              function groupById(arr){
              arr.sort((a,b)=>a.id-b.id);
              let arrNew = ;
              let min=0, max=0, currentid = arr[0].id;
              for(i=1; i<arr.length+1;i++){
              if(!arr[i] || arr[i].id!=currentid){
              arrNew.push({id:currentid, start:arr[min].start, end: arr[max].end});
              min = i;max=i;currentid=(arr[i]||{}).id;
              }
              if(!arr[i]){
              break;
              }
              if(arr[i].start<arr[min].start){
              min = i;
              }
              if(arr[i].end>arr[max].end){
              max = i;
              }
              }
              return arrNew;
              }

              var result = groupById([
              {"id":1, "start":"2018-10-10", "end":"2018-11-10"},
              {"id":1, "start":"2018-11-10", "end":"2018-12-10"},
              {"id":2, "start":"2018-11-22", "end":"2018-11-30"}
              ]);

              console.log(result);








              share|improve this answer













              What you are trying to do will require a custom solution where you merge two entries. In the below function I have iterated your array in chunks of same id first I have sorted it based on id and kept a min and max of the index where your logic says on date






              function groupById(arr){
              arr.sort((a,b)=>a.id-b.id);
              let arrNew = ;
              let min=0, max=0, currentid = arr[0].id;
              for(i=1; i<arr.length+1;i++){
              if(!arr[i] || arr[i].id!=currentid){
              arrNew.push({id:currentid, start:arr[min].start, end: arr[max].end});
              min = i;max=i;currentid=(arr[i]||{}).id;
              }
              if(!arr[i]){
              break;
              }
              if(arr[i].start<arr[min].start){
              min = i;
              }
              if(arr[i].end>arr[max].end){
              max = i;
              }
              }
              return arrNew;
              }

              var result = groupById([
              {"id":1, "start":"2018-10-10", "end":"2018-11-10"},
              {"id":1, "start":"2018-11-10", "end":"2018-12-10"},
              {"id":2, "start":"2018-11-22", "end":"2018-11-30"}
              ]);

              console.log(result);








              function groupById(arr){
              arr.sort((a,b)=>a.id-b.id);
              let arrNew = ;
              let min=0, max=0, currentid = arr[0].id;
              for(i=1; i<arr.length+1;i++){
              if(!arr[i] || arr[i].id!=currentid){
              arrNew.push({id:currentid, start:arr[min].start, end: arr[max].end});
              min = i;max=i;currentid=(arr[i]||{}).id;
              }
              if(!arr[i]){
              break;
              }
              if(arr[i].start<arr[min].start){
              min = i;
              }
              if(arr[i].end>arr[max].end){
              max = i;
              }
              }
              return arrNew;
              }

              var result = groupById([
              {"id":1, "start":"2018-10-10", "end":"2018-11-10"},
              {"id":1, "start":"2018-11-10", "end":"2018-12-10"},
              {"id":2, "start":"2018-11-22", "end":"2018-11-30"}
              ]);

              console.log(result);





              function groupById(arr){
              arr.sort((a,b)=>a.id-b.id);
              let arrNew = ;
              let min=0, max=0, currentid = arr[0].id;
              for(i=1; i<arr.length+1;i++){
              if(!arr[i] || arr[i].id!=currentid){
              arrNew.push({id:currentid, start:arr[min].start, end: arr[max].end});
              min = i;max=i;currentid=(arr[i]||{}).id;
              }
              if(!arr[i]){
              break;
              }
              if(arr[i].start<arr[min].start){
              min = i;
              }
              if(arr[i].end>arr[max].end){
              max = i;
              }
              }
              return arrNew;
              }

              var result = groupById([
              {"id":1, "start":"2018-10-10", "end":"2018-11-10"},
              {"id":1, "start":"2018-11-10", "end":"2018-12-10"},
              {"id":2, "start":"2018-11-22", "end":"2018-11-30"}
              ]);

              console.log(result);






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 20 '18 at 8:48









              joyBlanksjoyBlanks

              3,61611036




              3,61611036

























                  0














                  you need to sort array using date comparison and also reduce it by id.



                  var data = [{
                  "id": 1,
                  "start": "2018-10-10",
                  "end": "2018-11-10"
                  },
                  {
                  "id": 1,
                  "start": "2018-11-10",
                  "end": "2018-12-10"
                  },
                  {
                  "id": 2,
                  "start": "2018-11-22",
                  "end": "2018-11-30"
                  }
                  ];


                  let result = data.sort((a, b) => new Date(a.start) > new Date(b.start)).reduce(function(r, a) {
                  if (!r[a.id] || r[a.id][0].id !== a.id) {
                  r[a.id] = r[a.id] || ;
                  r[a.id].push(a);
                  }

                  return r;
                  }, Object.create(null));

                  console.log(result)





                  share|improve this answer




























                    0














                    you need to sort array using date comparison and also reduce it by id.



                    var data = [{
                    "id": 1,
                    "start": "2018-10-10",
                    "end": "2018-11-10"
                    },
                    {
                    "id": 1,
                    "start": "2018-11-10",
                    "end": "2018-12-10"
                    },
                    {
                    "id": 2,
                    "start": "2018-11-22",
                    "end": "2018-11-30"
                    }
                    ];


                    let result = data.sort((a, b) => new Date(a.start) > new Date(b.start)).reduce(function(r, a) {
                    if (!r[a.id] || r[a.id][0].id !== a.id) {
                    r[a.id] = r[a.id] || ;
                    r[a.id].push(a);
                    }

                    return r;
                    }, Object.create(null));

                    console.log(result)





                    share|improve this answer


























                      0












                      0








                      0







                      you need to sort array using date comparison and also reduce it by id.



                      var data = [{
                      "id": 1,
                      "start": "2018-10-10",
                      "end": "2018-11-10"
                      },
                      {
                      "id": 1,
                      "start": "2018-11-10",
                      "end": "2018-12-10"
                      },
                      {
                      "id": 2,
                      "start": "2018-11-22",
                      "end": "2018-11-30"
                      }
                      ];


                      let result = data.sort((a, b) => new Date(a.start) > new Date(b.start)).reduce(function(r, a) {
                      if (!r[a.id] || r[a.id][0].id !== a.id) {
                      r[a.id] = r[a.id] || ;
                      r[a.id].push(a);
                      }

                      return r;
                      }, Object.create(null));

                      console.log(result)





                      share|improve this answer













                      you need to sort array using date comparison and also reduce it by id.



                      var data = [{
                      "id": 1,
                      "start": "2018-10-10",
                      "end": "2018-11-10"
                      },
                      {
                      "id": 1,
                      "start": "2018-11-10",
                      "end": "2018-12-10"
                      },
                      {
                      "id": 2,
                      "start": "2018-11-22",
                      "end": "2018-11-30"
                      }
                      ];


                      let result = data.sort((a, b) => new Date(a.start) > new Date(b.start)).reduce(function(r, a) {
                      if (!r[a.id] || r[a.id][0].id !== a.id) {
                      r[a.id] = r[a.id] || ;
                      r[a.id].push(a);
                      }

                      return r;
                      }, Object.create(null));

                      console.log(result)






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 20 '18 at 8:49









                      dganencodganenco

                      2217




                      2217























                          0














                          You seem to be having multiple things that need to be grouped and reduces (as shown by comment referring to other question). So I will provide some general methods in this answer.



                          MDN has excelent documentation on all methods used here like map, reduce and Object.value, I would advice you have a look there to understand the code better.



                          ES6 syntax is explained very well here






                          const data = [
                          { id: 1, start: '2018-10-10', end: '2018-11-10' },
                          { id: 1, start: '2018-11-10', end: '2018-12-10' },
                          { id: 2, start: '2018-11-22', end: '2018-11-30' },
                          ];

                          const groupBy = (arr, key) =>
                          arr.reduce(
                          (result, item) => (
                          result[item[key]].push(item), result
                          ),
                          arr.reduce(
                          (result, item) => ((result[item[key]] = ), result),
                          {},
                          ),
                          );
                          const returnLowHigh = (comp) => (a, b) =>
                          a.localeCompare(b) === comp ? a : b;
                          const lowest = returnLowHigh(-1);
                          const highest = returnLowHigh(1);
                          console.log(
                          Object.values(groupBy(data, 'id')).map((items) =>
                          items.reduce((result, { id, start, end }) => ({
                          id,
                          start: lowest(result.start, start),
                          end: highest(result.end, end),
                          })),
                          ),
                          );








                          share|improve this answer




























                            0














                            You seem to be having multiple things that need to be grouped and reduces (as shown by comment referring to other question). So I will provide some general methods in this answer.



                            MDN has excelent documentation on all methods used here like map, reduce and Object.value, I would advice you have a look there to understand the code better.



                            ES6 syntax is explained very well here






                            const data = [
                            { id: 1, start: '2018-10-10', end: '2018-11-10' },
                            { id: 1, start: '2018-11-10', end: '2018-12-10' },
                            { id: 2, start: '2018-11-22', end: '2018-11-30' },
                            ];

                            const groupBy = (arr, key) =>
                            arr.reduce(
                            (result, item) => (
                            result[item[key]].push(item), result
                            ),
                            arr.reduce(
                            (result, item) => ((result[item[key]] = ), result),
                            {},
                            ),
                            );
                            const returnLowHigh = (comp) => (a, b) =>
                            a.localeCompare(b) === comp ? a : b;
                            const lowest = returnLowHigh(-1);
                            const highest = returnLowHigh(1);
                            console.log(
                            Object.values(groupBy(data, 'id')).map((items) =>
                            items.reduce((result, { id, start, end }) => ({
                            id,
                            start: lowest(result.start, start),
                            end: highest(result.end, end),
                            })),
                            ),
                            );








                            share|improve this answer


























                              0












                              0








                              0







                              You seem to be having multiple things that need to be grouped and reduces (as shown by comment referring to other question). So I will provide some general methods in this answer.



                              MDN has excelent documentation on all methods used here like map, reduce and Object.value, I would advice you have a look there to understand the code better.



                              ES6 syntax is explained very well here






                              const data = [
                              { id: 1, start: '2018-10-10', end: '2018-11-10' },
                              { id: 1, start: '2018-11-10', end: '2018-12-10' },
                              { id: 2, start: '2018-11-22', end: '2018-11-30' },
                              ];

                              const groupBy = (arr, key) =>
                              arr.reduce(
                              (result, item) => (
                              result[item[key]].push(item), result
                              ),
                              arr.reduce(
                              (result, item) => ((result[item[key]] = ), result),
                              {},
                              ),
                              );
                              const returnLowHigh = (comp) => (a, b) =>
                              a.localeCompare(b) === comp ? a : b;
                              const lowest = returnLowHigh(-1);
                              const highest = returnLowHigh(1);
                              console.log(
                              Object.values(groupBy(data, 'id')).map((items) =>
                              items.reduce((result, { id, start, end }) => ({
                              id,
                              start: lowest(result.start, start),
                              end: highest(result.end, end),
                              })),
                              ),
                              );








                              share|improve this answer













                              You seem to be having multiple things that need to be grouped and reduces (as shown by comment referring to other question). So I will provide some general methods in this answer.



                              MDN has excelent documentation on all methods used here like map, reduce and Object.value, I would advice you have a look there to understand the code better.



                              ES6 syntax is explained very well here






                              const data = [
                              { id: 1, start: '2018-10-10', end: '2018-11-10' },
                              { id: 1, start: '2018-11-10', end: '2018-12-10' },
                              { id: 2, start: '2018-11-22', end: '2018-11-30' },
                              ];

                              const groupBy = (arr, key) =>
                              arr.reduce(
                              (result, item) => (
                              result[item[key]].push(item), result
                              ),
                              arr.reduce(
                              (result, item) => ((result[item[key]] = ), result),
                              {},
                              ),
                              );
                              const returnLowHigh = (comp) => (a, b) =>
                              a.localeCompare(b) === comp ? a : b;
                              const lowest = returnLowHigh(-1);
                              const highest = returnLowHigh(1);
                              console.log(
                              Object.values(groupBy(data, 'id')).map((items) =>
                              items.reduce((result, { id, start, end }) => ({
                              id,
                              start: lowest(result.start, start),
                              end: highest(result.end, end),
                              })),
                              ),
                              );








                              const data = [
                              { id: 1, start: '2018-10-10', end: '2018-11-10' },
                              { id: 1, start: '2018-11-10', end: '2018-12-10' },
                              { id: 2, start: '2018-11-22', end: '2018-11-30' },
                              ];

                              const groupBy = (arr, key) =>
                              arr.reduce(
                              (result, item) => (
                              result[item[key]].push(item), result
                              ),
                              arr.reduce(
                              (result, item) => ((result[item[key]] = ), result),
                              {},
                              ),
                              );
                              const returnLowHigh = (comp) => (a, b) =>
                              a.localeCompare(b) === comp ? a : b;
                              const lowest = returnLowHigh(-1);
                              const highest = returnLowHigh(1);
                              console.log(
                              Object.values(groupBy(data, 'id')).map((items) =>
                              items.reduce((result, { id, start, end }) => ({
                              id,
                              start: lowest(result.start, start),
                              end: highest(result.end, end),
                              })),
                              ),
                              );





                              const data = [
                              { id: 1, start: '2018-10-10', end: '2018-11-10' },
                              { id: 1, start: '2018-11-10', end: '2018-12-10' },
                              { id: 2, start: '2018-11-22', end: '2018-11-30' },
                              ];

                              const groupBy = (arr, key) =>
                              arr.reduce(
                              (result, item) => (
                              result[item[key]].push(item), result
                              ),
                              arr.reduce(
                              (result, item) => ((result[item[key]] = ), result),
                              {},
                              ),
                              );
                              const returnLowHigh = (comp) => (a, b) =>
                              a.localeCompare(b) === comp ? a : b;
                              const lowest = returnLowHigh(-1);
                              const highest = returnLowHigh(1);
                              console.log(
                              Object.values(groupBy(data, 'id')).map((items) =>
                              items.reduce((result, { id, start, end }) => ({
                              id,
                              start: lowest(result.start, start),
                              end: highest(result.end, end),
                              })),
                              ),
                              );






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 20 '18 at 9:04









                              HMRHMR

                              13.9k113899




                              13.9k113899























                                  0














                                  You can use reduce function and check the start and end date and if start date






                                  let old = [{
                                  "id": 1,
                                  "start": "2018-10-10",
                                  "end": "2018-11-10"
                                  },
                                  {
                                  "id": 1,
                                  "start": "2018-11-10",
                                  "end": "2018-12-10"
                                  },
                                  {
                                  "id": 2,
                                  "start": "2018-11-22",
                                  "end": "2018-11-30"
                                  }
                                  ];

                                  let k = old.reduce(function(acc, curr) {
                                  let findId = acc.findIndex((item) => {
                                  return item.id === curr.id
                                  });

                                  if (findId === -1) {
                                  acc.push(curr)
                                  } else {
                                  let oldStartDate = createDate(acc[findId].start);
                                  let newStartDate = createDate(curr.start);
                                  let oldEndDate = createDate(acc[findId].end);
                                  let newEndDate = createDate(curr.end);


                                  if (newStartDate < oldStartDate) {

                                  acc[findId].start = curr.start
                                  }
                                  if (newEndDate > oldEndDate) {

                                  acc[findId].end = curr.end
                                  }

                                  }

                                  return acc;

                                  }, );

                                  console.log(k);

                                  function createDate(dte) {
                                  let dt = new Date(dte);
                                  return `${dt.getYear()}-${dt.getMonth()}-${dt.getDate()}`

                                  }








                                  share|improve this answer




























                                    0














                                    You can use reduce function and check the start and end date and if start date






                                    let old = [{
                                    "id": 1,
                                    "start": "2018-10-10",
                                    "end": "2018-11-10"
                                    },
                                    {
                                    "id": 1,
                                    "start": "2018-11-10",
                                    "end": "2018-12-10"
                                    },
                                    {
                                    "id": 2,
                                    "start": "2018-11-22",
                                    "end": "2018-11-30"
                                    }
                                    ];

                                    let k = old.reduce(function(acc, curr) {
                                    let findId = acc.findIndex((item) => {
                                    return item.id === curr.id
                                    });

                                    if (findId === -1) {
                                    acc.push(curr)
                                    } else {
                                    let oldStartDate = createDate(acc[findId].start);
                                    let newStartDate = createDate(curr.start);
                                    let oldEndDate = createDate(acc[findId].end);
                                    let newEndDate = createDate(curr.end);


                                    if (newStartDate < oldStartDate) {

                                    acc[findId].start = curr.start
                                    }
                                    if (newEndDate > oldEndDate) {

                                    acc[findId].end = curr.end
                                    }

                                    }

                                    return acc;

                                    }, );

                                    console.log(k);

                                    function createDate(dte) {
                                    let dt = new Date(dte);
                                    return `${dt.getYear()}-${dt.getMonth()}-${dt.getDate()}`

                                    }








                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      You can use reduce function and check the start and end date and if start date






                                      let old = [{
                                      "id": 1,
                                      "start": "2018-10-10",
                                      "end": "2018-11-10"
                                      },
                                      {
                                      "id": 1,
                                      "start": "2018-11-10",
                                      "end": "2018-12-10"
                                      },
                                      {
                                      "id": 2,
                                      "start": "2018-11-22",
                                      "end": "2018-11-30"
                                      }
                                      ];

                                      let k = old.reduce(function(acc, curr) {
                                      let findId = acc.findIndex((item) => {
                                      return item.id === curr.id
                                      });

                                      if (findId === -1) {
                                      acc.push(curr)
                                      } else {
                                      let oldStartDate = createDate(acc[findId].start);
                                      let newStartDate = createDate(curr.start);
                                      let oldEndDate = createDate(acc[findId].end);
                                      let newEndDate = createDate(curr.end);


                                      if (newStartDate < oldStartDate) {

                                      acc[findId].start = curr.start
                                      }
                                      if (newEndDate > oldEndDate) {

                                      acc[findId].end = curr.end
                                      }

                                      }

                                      return acc;

                                      }, );

                                      console.log(k);

                                      function createDate(dte) {
                                      let dt = new Date(dte);
                                      return `${dt.getYear()}-${dt.getMonth()}-${dt.getDate()}`

                                      }








                                      share|improve this answer













                                      You can use reduce function and check the start and end date and if start date






                                      let old = [{
                                      "id": 1,
                                      "start": "2018-10-10",
                                      "end": "2018-11-10"
                                      },
                                      {
                                      "id": 1,
                                      "start": "2018-11-10",
                                      "end": "2018-12-10"
                                      },
                                      {
                                      "id": 2,
                                      "start": "2018-11-22",
                                      "end": "2018-11-30"
                                      }
                                      ];

                                      let k = old.reduce(function(acc, curr) {
                                      let findId = acc.findIndex((item) => {
                                      return item.id === curr.id
                                      });

                                      if (findId === -1) {
                                      acc.push(curr)
                                      } else {
                                      let oldStartDate = createDate(acc[findId].start);
                                      let newStartDate = createDate(curr.start);
                                      let oldEndDate = createDate(acc[findId].end);
                                      let newEndDate = createDate(curr.end);


                                      if (newStartDate < oldStartDate) {

                                      acc[findId].start = curr.start
                                      }
                                      if (newEndDate > oldEndDate) {

                                      acc[findId].end = curr.end
                                      }

                                      }

                                      return acc;

                                      }, );

                                      console.log(k);

                                      function createDate(dte) {
                                      let dt = new Date(dte);
                                      return `${dt.getYear()}-${dt.getMonth()}-${dt.getDate()}`

                                      }








                                      let old = [{
                                      "id": 1,
                                      "start": "2018-10-10",
                                      "end": "2018-11-10"
                                      },
                                      {
                                      "id": 1,
                                      "start": "2018-11-10",
                                      "end": "2018-12-10"
                                      },
                                      {
                                      "id": 2,
                                      "start": "2018-11-22",
                                      "end": "2018-11-30"
                                      }
                                      ];

                                      let k = old.reduce(function(acc, curr) {
                                      let findId = acc.findIndex((item) => {
                                      return item.id === curr.id
                                      });

                                      if (findId === -1) {
                                      acc.push(curr)
                                      } else {
                                      let oldStartDate = createDate(acc[findId].start);
                                      let newStartDate = createDate(curr.start);
                                      let oldEndDate = createDate(acc[findId].end);
                                      let newEndDate = createDate(curr.end);


                                      if (newStartDate < oldStartDate) {

                                      acc[findId].start = curr.start
                                      }
                                      if (newEndDate > oldEndDate) {

                                      acc[findId].end = curr.end
                                      }

                                      }

                                      return acc;

                                      }, );

                                      console.log(k);

                                      function createDate(dte) {
                                      let dt = new Date(dte);
                                      return `${dt.getYear()}-${dt.getMonth()}-${dt.getDate()}`

                                      }





                                      let old = [{
                                      "id": 1,
                                      "start": "2018-10-10",
                                      "end": "2018-11-10"
                                      },
                                      {
                                      "id": 1,
                                      "start": "2018-11-10",
                                      "end": "2018-12-10"
                                      },
                                      {
                                      "id": 2,
                                      "start": "2018-11-22",
                                      "end": "2018-11-30"
                                      }
                                      ];

                                      let k = old.reduce(function(acc, curr) {
                                      let findId = acc.findIndex((item) => {
                                      return item.id === curr.id
                                      });

                                      if (findId === -1) {
                                      acc.push(curr)
                                      } else {
                                      let oldStartDate = createDate(acc[findId].start);
                                      let newStartDate = createDate(curr.start);
                                      let oldEndDate = createDate(acc[findId].end);
                                      let newEndDate = createDate(curr.end);


                                      if (newStartDate < oldStartDate) {

                                      acc[findId].start = curr.start
                                      }
                                      if (newEndDate > oldEndDate) {

                                      acc[findId].end = curr.end
                                      }

                                      }

                                      return acc;

                                      }, );

                                      console.log(k);

                                      function createDate(dte) {
                                      let dt = new Date(dte);
                                      return `${dt.getYear()}-${dt.getMonth()}-${dt.getDate()}`

                                      }






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 20 '18 at 9:09









                                      brkbrk

                                      27.4k32141




                                      27.4k32141






























                                          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%2f53388901%2fhow-to-get-the-minimum-and-maximum-date-and-grouped-it-by-id%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







                                          這個網誌中的熱門文章

                                          Academy of Television Arts & Sciences

                                          L'Équipe

                                          1995 France bombings