Split an array of items into several arrays, given a conditionTransforming an array of arrays into an array...

Why doesn't "auto ch = unsigned char{'p'}" compile under C++ 17?

Pre-1980's science fiction short story: alien disguised as a woman shot by a gangster, has tentacles coming out of her breasts when remaking her body

Parsing a string of key-value pairs as a dictionary

Compress command output by piping to bzip2

Groups acting on trees

Isn't using the Extrusion Multiplier like cheating?

Contest math problem about crossing out numbers in the table

Broken patches on a road

Jumping Numbers

Quenching swords in dragon blood; why?

Can you earn endless XP using a Flameskull and its self-revival feature?

How to explain planetary rings pulsating?

Is there some relative to Dutch word "kijken" in German?

Am I a Rude Number?

The effects of magnetism in radio transmissions

Book where aliens are selecting humans for food consumption

Monthly Patch Releases for Linux CentOS/RedHat

Would a National Army of mercenaries be a feasible idea?

What is the purpose of easy combat scenarios that don't need resource expenditure?

Dilemma of explaining to interviewer that he is the reason for declining second interview

Typing Amharic inside a math equation?

Word or phrase for showing great skill at something without formal training in it

How should I handle players who ignore the session zero agreement?

Using only 1s, make 29 with the minimum number of digits



Split an array of items into several arrays, given a condition


Transforming an array of arrays into an array with joinsSimple multi-dimensional Array class in C++11 - follow-upGroup similar objects into array of arraysMerging multiple sorted arrays into one sorted arrayIf given two sorted arrays where first containing -1, merge into one sorted arrayCreate several homogeneous arrays from a larger heterogenous array efficientlyConsole Address Book applicationCount arrays' of objects intersections based on several propertiesTraversing through single large array to convert single array into array of arrays as per conditionMove objects into embedded arrays













2












$begingroup$


The question is very simple : I have an array of items, that all have a date. According to the date, I would like to split this array into several arrays.



In my case, I would like to split the array into 3 arrays : one that contains result of the last 24h, the other 48h, then the last one on the week.



Here is a minimal reproduction of the case, with the final solution.






const now = Date.now();
const day = 1000 * 3600 * 24;

const todayTime = now - day;
const yesterdayTime = now - day * 2;
const weekTime = now - day * 7;

const arr = [
{ id: 1, date: todayTime + 100 },
{ id: 2, date: yesterdayTime + 100 },
{ id: 3, date: weekTime + 100 },
];

const today = arr.filter(item => item.date - todayTime > 0);
const yesterday = arr.filter(item => item.date - yesterdayTime > 0 && item.date - todayTime < 0);
const week = arr.filter(item => item.date - weekTime > 0 && item.date - yesterdayTime < 0);

console.log(today, yesterday, week);





Is there a way to make it more concise ? I'm talking about code length : I would like to reduce it to the maximum, especially the definition of the 3 arrays. I tried with reduce, but the syntax is pretty ugly.



Any ideas ?










share|improve this question







New contributor




trichetriche is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    2












    $begingroup$


    The question is very simple : I have an array of items, that all have a date. According to the date, I would like to split this array into several arrays.



    In my case, I would like to split the array into 3 arrays : one that contains result of the last 24h, the other 48h, then the last one on the week.



    Here is a minimal reproduction of the case, with the final solution.






    const now = Date.now();
    const day = 1000 * 3600 * 24;

    const todayTime = now - day;
    const yesterdayTime = now - day * 2;
    const weekTime = now - day * 7;

    const arr = [
    { id: 1, date: todayTime + 100 },
    { id: 2, date: yesterdayTime + 100 },
    { id: 3, date: weekTime + 100 },
    ];

    const today = arr.filter(item => item.date - todayTime > 0);
    const yesterday = arr.filter(item => item.date - yesterdayTime > 0 && item.date - todayTime < 0);
    const week = arr.filter(item => item.date - weekTime > 0 && item.date - yesterdayTime < 0);

    console.log(today, yesterday, week);





    Is there a way to make it more concise ? I'm talking about code length : I would like to reduce it to the maximum, especially the definition of the 3 arrays. I tried with reduce, but the syntax is pretty ugly.



    Any ideas ?










    share|improve this question







    New contributor




    trichetriche is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      2












      2








      2





      $begingroup$


      The question is very simple : I have an array of items, that all have a date. According to the date, I would like to split this array into several arrays.



      In my case, I would like to split the array into 3 arrays : one that contains result of the last 24h, the other 48h, then the last one on the week.



      Here is a minimal reproduction of the case, with the final solution.






      const now = Date.now();
      const day = 1000 * 3600 * 24;

      const todayTime = now - day;
      const yesterdayTime = now - day * 2;
      const weekTime = now - day * 7;

      const arr = [
      { id: 1, date: todayTime + 100 },
      { id: 2, date: yesterdayTime + 100 },
      { id: 3, date: weekTime + 100 },
      ];

      const today = arr.filter(item => item.date - todayTime > 0);
      const yesterday = arr.filter(item => item.date - yesterdayTime > 0 && item.date - todayTime < 0);
      const week = arr.filter(item => item.date - weekTime > 0 && item.date - yesterdayTime < 0);

      console.log(today, yesterday, week);





      Is there a way to make it more concise ? I'm talking about code length : I would like to reduce it to the maximum, especially the definition of the 3 arrays. I tried with reduce, but the syntax is pretty ugly.



      Any ideas ?










      share|improve this question







      New contributor




      trichetriche is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      The question is very simple : I have an array of items, that all have a date. According to the date, I would like to split this array into several arrays.



      In my case, I would like to split the array into 3 arrays : one that contains result of the last 24h, the other 48h, then the last one on the week.



      Here is a minimal reproduction of the case, with the final solution.






      const now = Date.now();
      const day = 1000 * 3600 * 24;

      const todayTime = now - day;
      const yesterdayTime = now - day * 2;
      const weekTime = now - day * 7;

      const arr = [
      { id: 1, date: todayTime + 100 },
      { id: 2, date: yesterdayTime + 100 },
      { id: 3, date: weekTime + 100 },
      ];

      const today = arr.filter(item => item.date - todayTime > 0);
      const yesterday = arr.filter(item => item.date - yesterdayTime > 0 && item.date - todayTime < 0);
      const week = arr.filter(item => item.date - weekTime > 0 && item.date - yesterdayTime < 0);

      console.log(today, yesterday, week);





      Is there a way to make it more concise ? I'm talking about code length : I would like to reduce it to the maximum, especially the definition of the 3 arrays. I tried with reduce, but the syntax is pretty ugly.



      Any ideas ?






      const now = Date.now();
      const day = 1000 * 3600 * 24;

      const todayTime = now - day;
      const yesterdayTime = now - day * 2;
      const weekTime = now - day * 7;

      const arr = [
      { id: 1, date: todayTime + 100 },
      { id: 2, date: yesterdayTime + 100 },
      { id: 3, date: weekTime + 100 },
      ];

      const today = arr.filter(item => item.date - todayTime > 0);
      const yesterday = arr.filter(item => item.date - yesterdayTime > 0 && item.date - todayTime < 0);
      const week = arr.filter(item => item.date - weekTime > 0 && item.date - yesterdayTime < 0);

      console.log(today, yesterday, week);





      const now = Date.now();
      const day = 1000 * 3600 * 24;

      const todayTime = now - day;
      const yesterdayTime = now - day * 2;
      const weekTime = now - day * 7;

      const arr = [
      { id: 1, date: todayTime + 100 },
      { id: 2, date: yesterdayTime + 100 },
      { id: 3, date: weekTime + 100 },
      ];

      const today = arr.filter(item => item.date - todayTime > 0);
      const yesterday = arr.filter(item => item.date - yesterdayTime > 0 && item.date - todayTime < 0);
      const week = arr.filter(item => item.date - weekTime > 0 && item.date - yesterdayTime < 0);

      console.log(today, yesterday, week);






      javascript array






      share|improve this question







      New contributor




      trichetriche is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      trichetriche is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      trichetriche is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 13 hours ago









      trichetrichetrichetriche

      1114




      1114




      New contributor




      trichetriche is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      trichetriche is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      trichetriche is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          2 Answers
          2






          active

          oldest

          votes


















          1












          $begingroup$

          item.date - todayTime > 0 is the same as item.date > todayTime.



          Your less-than condition should be less-than-or-equal, otherwise anything falling on a day boundary won't match any category.






          const now = Date.now(),
          day = 1000 * 3600 * 24,
          arr = [
          { id: 1, date: now - day + 100 },
          { id: 2, date: now - day*2 + 100 },
          { id: 3, date: now - day*7 + 100 },
          ],
          daysAgo=[ 1, 2, 7 ],
          filtered=daysAgo.map(
          (days,i) => arr.filter(
          j => j.date > now-day*days && j.date <= now-day*( i ? daysAgo[i-1] : -1 )
          )
          );

          console.log(filtered);








          share|improve this answer









          $endgroup$













          • $begingroup$
            As said on your previous comment, I just wrote that fast and didn't really cared about all that. I was more focused on the array operators
            $endgroup$
            – trichetriche
            11 hours ago










          • $begingroup$
            well you can factor out some of the calculations with an array of days - see my code. It's only a little shorter than your version, but it will scale up to many intervals with hardly any increase in code length.
            $endgroup$
            – Oh My Goodness
            11 hours ago










          • $begingroup$
            I have posted this question on SOF and they made the same statement, to which I replied that my case is very specific and I actually don't need genericity, because the data that is one week old gets deleted. I have and will always have 3 arrays, so I don't need to make it generic at all. But your answer is nicely thought indeed, so have my upvote !
            $endgroup$
            – trichetriche
            10 hours ago



















          1












          $begingroup$

          Always create a function



          Its not really code if its not a function, you may as well just output the 3 arrays directly. (my personal view on global inline code).



          You may say, "This is just an example". No it can not be just an example, a function has special powers and is written differently than inline code. Plus examples are boarder line off topic here, this question may get closed.



          Part of a functions power is that it makes you think about how you solve the problem differently from inline code.



          Look for change



          When you write a function you look for the parts of the logic and data that change. You pass that to the function as arguments. The function uses these argument to process the data and return the desired results.



          In this case you have




          • the array of items to split.

          • The number of days old to split the data, eg 1,2,and 7 days.


          Thus we can have something like the following. The function is declared inside another so that all it needs is safely encapsulated and outside of unrelated scopes.



          const splitByDaysOld = (() => {
          const MS_IN_DAY = 8.64e7;
          const sorter = (a, b) => a - b;
          return function(array, periods) {
          const now = Date.now();
          var start = 0;
          return periods.sort(sorter).map(day => {
          const res = array.filter(item => {
          const daysOld = (item.date - now) / MS_IN_DAY;
          return daysOld >= start && daysOld < day;
          });
          start = day;
          return res;
          });
          };
          })();


          It returns an array of arrays, one for each period.



          Example below has 3 periods 0 to < 1, 1 to < 2, and 2 to < 7 days old.



          const [today, yesterday, week] = splitByDaysOld(arr, [1, 2, 7]);


          Note that the periods array is sorted from most recent to oldest and that the result will be in the same order






          share|improve this answer









          $endgroup$













          • $begingroup$
            The function is called listAllPercos and it exists. So yes, it is just an example. Didn't think about making it like this though. Question totally out of context, but is this considerd a factory ? And I'm going to try to implement it with what I need and don't, and keep you updated. Anyway, have my upvote too !
            $endgroup$
            – trichetriche
            10 hours ago











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          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: "196"
          };
          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: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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
          });


          }
          });






          trichetriche is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214540%2fsplit-an-array-of-items-into-several-arrays-given-a-condition%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1












          $begingroup$

          item.date - todayTime > 0 is the same as item.date > todayTime.



          Your less-than condition should be less-than-or-equal, otherwise anything falling on a day boundary won't match any category.






          const now = Date.now(),
          day = 1000 * 3600 * 24,
          arr = [
          { id: 1, date: now - day + 100 },
          { id: 2, date: now - day*2 + 100 },
          { id: 3, date: now - day*7 + 100 },
          ],
          daysAgo=[ 1, 2, 7 ],
          filtered=daysAgo.map(
          (days,i) => arr.filter(
          j => j.date > now-day*days && j.date <= now-day*( i ? daysAgo[i-1] : -1 )
          )
          );

          console.log(filtered);








          share|improve this answer









          $endgroup$













          • $begingroup$
            As said on your previous comment, I just wrote that fast and didn't really cared about all that. I was more focused on the array operators
            $endgroup$
            – trichetriche
            11 hours ago










          • $begingroup$
            well you can factor out some of the calculations with an array of days - see my code. It's only a little shorter than your version, but it will scale up to many intervals with hardly any increase in code length.
            $endgroup$
            – Oh My Goodness
            11 hours ago










          • $begingroup$
            I have posted this question on SOF and they made the same statement, to which I replied that my case is very specific and I actually don't need genericity, because the data that is one week old gets deleted. I have and will always have 3 arrays, so I don't need to make it generic at all. But your answer is nicely thought indeed, so have my upvote !
            $endgroup$
            – trichetriche
            10 hours ago
















          1












          $begingroup$

          item.date - todayTime > 0 is the same as item.date > todayTime.



          Your less-than condition should be less-than-or-equal, otherwise anything falling on a day boundary won't match any category.






          const now = Date.now(),
          day = 1000 * 3600 * 24,
          arr = [
          { id: 1, date: now - day + 100 },
          { id: 2, date: now - day*2 + 100 },
          { id: 3, date: now - day*7 + 100 },
          ],
          daysAgo=[ 1, 2, 7 ],
          filtered=daysAgo.map(
          (days,i) => arr.filter(
          j => j.date > now-day*days && j.date <= now-day*( i ? daysAgo[i-1] : -1 )
          )
          );

          console.log(filtered);








          share|improve this answer









          $endgroup$













          • $begingroup$
            As said on your previous comment, I just wrote that fast and didn't really cared about all that. I was more focused on the array operators
            $endgroup$
            – trichetriche
            11 hours ago










          • $begingroup$
            well you can factor out some of the calculations with an array of days - see my code. It's only a little shorter than your version, but it will scale up to many intervals with hardly any increase in code length.
            $endgroup$
            – Oh My Goodness
            11 hours ago










          • $begingroup$
            I have posted this question on SOF and they made the same statement, to which I replied that my case is very specific and I actually don't need genericity, because the data that is one week old gets deleted. I have and will always have 3 arrays, so I don't need to make it generic at all. But your answer is nicely thought indeed, so have my upvote !
            $endgroup$
            – trichetriche
            10 hours ago














          1












          1








          1





          $begingroup$

          item.date - todayTime > 0 is the same as item.date > todayTime.



          Your less-than condition should be less-than-or-equal, otherwise anything falling on a day boundary won't match any category.






          const now = Date.now(),
          day = 1000 * 3600 * 24,
          arr = [
          { id: 1, date: now - day + 100 },
          { id: 2, date: now - day*2 + 100 },
          { id: 3, date: now - day*7 + 100 },
          ],
          daysAgo=[ 1, 2, 7 ],
          filtered=daysAgo.map(
          (days,i) => arr.filter(
          j => j.date > now-day*days && j.date <= now-day*( i ? daysAgo[i-1] : -1 )
          )
          );

          console.log(filtered);








          share|improve this answer









          $endgroup$



          item.date - todayTime > 0 is the same as item.date > todayTime.



          Your less-than condition should be less-than-or-equal, otherwise anything falling on a day boundary won't match any category.






          const now = Date.now(),
          day = 1000 * 3600 * 24,
          arr = [
          { id: 1, date: now - day + 100 },
          { id: 2, date: now - day*2 + 100 },
          { id: 3, date: now - day*7 + 100 },
          ],
          daysAgo=[ 1, 2, 7 ],
          filtered=daysAgo.map(
          (days,i) => arr.filter(
          j => j.date > now-day*days && j.date <= now-day*( i ? daysAgo[i-1] : -1 )
          )
          );

          console.log(filtered);








          const now = Date.now(),
          day = 1000 * 3600 * 24,
          arr = [
          { id: 1, date: now - day + 100 },
          { id: 2, date: now - day*2 + 100 },
          { id: 3, date: now - day*7 + 100 },
          ],
          daysAgo=[ 1, 2, 7 ],
          filtered=daysAgo.map(
          (days,i) => arr.filter(
          j => j.date > now-day*days && j.date <= now-day*( i ? daysAgo[i-1] : -1 )
          )
          );

          console.log(filtered);





          const now = Date.now(),
          day = 1000 * 3600 * 24,
          arr = [
          { id: 1, date: now - day + 100 },
          { id: 2, date: now - day*2 + 100 },
          { id: 3, date: now - day*7 + 100 },
          ],
          daysAgo=[ 1, 2, 7 ],
          filtered=daysAgo.map(
          (days,i) => arr.filter(
          j => j.date > now-day*days && j.date <= now-day*( i ? daysAgo[i-1] : -1 )
          )
          );

          console.log(filtered);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 12 hours ago









          Oh My GoodnessOh My Goodness

          58529




          58529












          • $begingroup$
            As said on your previous comment, I just wrote that fast and didn't really cared about all that. I was more focused on the array operators
            $endgroup$
            – trichetriche
            11 hours ago










          • $begingroup$
            well you can factor out some of the calculations with an array of days - see my code. It's only a little shorter than your version, but it will scale up to many intervals with hardly any increase in code length.
            $endgroup$
            – Oh My Goodness
            11 hours ago










          • $begingroup$
            I have posted this question on SOF and they made the same statement, to which I replied that my case is very specific and I actually don't need genericity, because the data that is one week old gets deleted. I have and will always have 3 arrays, so I don't need to make it generic at all. But your answer is nicely thought indeed, so have my upvote !
            $endgroup$
            – trichetriche
            10 hours ago


















          • $begingroup$
            As said on your previous comment, I just wrote that fast and didn't really cared about all that. I was more focused on the array operators
            $endgroup$
            – trichetriche
            11 hours ago










          • $begingroup$
            well you can factor out some of the calculations with an array of days - see my code. It's only a little shorter than your version, but it will scale up to many intervals with hardly any increase in code length.
            $endgroup$
            – Oh My Goodness
            11 hours ago










          • $begingroup$
            I have posted this question on SOF and they made the same statement, to which I replied that my case is very specific and I actually don't need genericity, because the data that is one week old gets deleted. I have and will always have 3 arrays, so I don't need to make it generic at all. But your answer is nicely thought indeed, so have my upvote !
            $endgroup$
            – trichetriche
            10 hours ago
















          $begingroup$
          As said on your previous comment, I just wrote that fast and didn't really cared about all that. I was more focused on the array operators
          $endgroup$
          – trichetriche
          11 hours ago




          $begingroup$
          As said on your previous comment, I just wrote that fast and didn't really cared about all that. I was more focused on the array operators
          $endgroup$
          – trichetriche
          11 hours ago












          $begingroup$
          well you can factor out some of the calculations with an array of days - see my code. It's only a little shorter than your version, but it will scale up to many intervals with hardly any increase in code length.
          $endgroup$
          – Oh My Goodness
          11 hours ago




          $begingroup$
          well you can factor out some of the calculations with an array of days - see my code. It's only a little shorter than your version, but it will scale up to many intervals with hardly any increase in code length.
          $endgroup$
          – Oh My Goodness
          11 hours ago












          $begingroup$
          I have posted this question on SOF and they made the same statement, to which I replied that my case is very specific and I actually don't need genericity, because the data that is one week old gets deleted. I have and will always have 3 arrays, so I don't need to make it generic at all. But your answer is nicely thought indeed, so have my upvote !
          $endgroup$
          – trichetriche
          10 hours ago




          $begingroup$
          I have posted this question on SOF and they made the same statement, to which I replied that my case is very specific and I actually don't need genericity, because the data that is one week old gets deleted. I have and will always have 3 arrays, so I don't need to make it generic at all. But your answer is nicely thought indeed, so have my upvote !
          $endgroup$
          – trichetriche
          10 hours ago













          1












          $begingroup$

          Always create a function



          Its not really code if its not a function, you may as well just output the 3 arrays directly. (my personal view on global inline code).



          You may say, "This is just an example". No it can not be just an example, a function has special powers and is written differently than inline code. Plus examples are boarder line off topic here, this question may get closed.



          Part of a functions power is that it makes you think about how you solve the problem differently from inline code.



          Look for change



          When you write a function you look for the parts of the logic and data that change. You pass that to the function as arguments. The function uses these argument to process the data and return the desired results.



          In this case you have




          • the array of items to split.

          • The number of days old to split the data, eg 1,2,and 7 days.


          Thus we can have something like the following. The function is declared inside another so that all it needs is safely encapsulated and outside of unrelated scopes.



          const splitByDaysOld = (() => {
          const MS_IN_DAY = 8.64e7;
          const sorter = (a, b) => a - b;
          return function(array, periods) {
          const now = Date.now();
          var start = 0;
          return periods.sort(sorter).map(day => {
          const res = array.filter(item => {
          const daysOld = (item.date - now) / MS_IN_DAY;
          return daysOld >= start && daysOld < day;
          });
          start = day;
          return res;
          });
          };
          })();


          It returns an array of arrays, one for each period.



          Example below has 3 periods 0 to < 1, 1 to < 2, and 2 to < 7 days old.



          const [today, yesterday, week] = splitByDaysOld(arr, [1, 2, 7]);


          Note that the periods array is sorted from most recent to oldest and that the result will be in the same order






          share|improve this answer









          $endgroup$













          • $begingroup$
            The function is called listAllPercos and it exists. So yes, it is just an example. Didn't think about making it like this though. Question totally out of context, but is this considerd a factory ? And I'm going to try to implement it with what I need and don't, and keep you updated. Anyway, have my upvote too !
            $endgroup$
            – trichetriche
            10 hours ago
















          1












          $begingroup$

          Always create a function



          Its not really code if its not a function, you may as well just output the 3 arrays directly. (my personal view on global inline code).



          You may say, "This is just an example". No it can not be just an example, a function has special powers and is written differently than inline code. Plus examples are boarder line off topic here, this question may get closed.



          Part of a functions power is that it makes you think about how you solve the problem differently from inline code.



          Look for change



          When you write a function you look for the parts of the logic and data that change. You pass that to the function as arguments. The function uses these argument to process the data and return the desired results.



          In this case you have




          • the array of items to split.

          • The number of days old to split the data, eg 1,2,and 7 days.


          Thus we can have something like the following. The function is declared inside another so that all it needs is safely encapsulated and outside of unrelated scopes.



          const splitByDaysOld = (() => {
          const MS_IN_DAY = 8.64e7;
          const sorter = (a, b) => a - b;
          return function(array, periods) {
          const now = Date.now();
          var start = 0;
          return periods.sort(sorter).map(day => {
          const res = array.filter(item => {
          const daysOld = (item.date - now) / MS_IN_DAY;
          return daysOld >= start && daysOld < day;
          });
          start = day;
          return res;
          });
          };
          })();


          It returns an array of arrays, one for each period.



          Example below has 3 periods 0 to < 1, 1 to < 2, and 2 to < 7 days old.



          const [today, yesterday, week] = splitByDaysOld(arr, [1, 2, 7]);


          Note that the periods array is sorted from most recent to oldest and that the result will be in the same order






          share|improve this answer









          $endgroup$













          • $begingroup$
            The function is called listAllPercos and it exists. So yes, it is just an example. Didn't think about making it like this though. Question totally out of context, but is this considerd a factory ? And I'm going to try to implement it with what I need and don't, and keep you updated. Anyway, have my upvote too !
            $endgroup$
            – trichetriche
            10 hours ago














          1












          1








          1





          $begingroup$

          Always create a function



          Its not really code if its not a function, you may as well just output the 3 arrays directly. (my personal view on global inline code).



          You may say, "This is just an example". No it can not be just an example, a function has special powers and is written differently than inline code. Plus examples are boarder line off topic here, this question may get closed.



          Part of a functions power is that it makes you think about how you solve the problem differently from inline code.



          Look for change



          When you write a function you look for the parts of the logic and data that change. You pass that to the function as arguments. The function uses these argument to process the data and return the desired results.



          In this case you have




          • the array of items to split.

          • The number of days old to split the data, eg 1,2,and 7 days.


          Thus we can have something like the following. The function is declared inside another so that all it needs is safely encapsulated and outside of unrelated scopes.



          const splitByDaysOld = (() => {
          const MS_IN_DAY = 8.64e7;
          const sorter = (a, b) => a - b;
          return function(array, periods) {
          const now = Date.now();
          var start = 0;
          return periods.sort(sorter).map(day => {
          const res = array.filter(item => {
          const daysOld = (item.date - now) / MS_IN_DAY;
          return daysOld >= start && daysOld < day;
          });
          start = day;
          return res;
          });
          };
          })();


          It returns an array of arrays, one for each period.



          Example below has 3 periods 0 to < 1, 1 to < 2, and 2 to < 7 days old.



          const [today, yesterday, week] = splitByDaysOld(arr, [1, 2, 7]);


          Note that the periods array is sorted from most recent to oldest and that the result will be in the same order






          share|improve this answer









          $endgroup$



          Always create a function



          Its not really code if its not a function, you may as well just output the 3 arrays directly. (my personal view on global inline code).



          You may say, "This is just an example". No it can not be just an example, a function has special powers and is written differently than inline code. Plus examples are boarder line off topic here, this question may get closed.



          Part of a functions power is that it makes you think about how you solve the problem differently from inline code.



          Look for change



          When you write a function you look for the parts of the logic and data that change. You pass that to the function as arguments. The function uses these argument to process the data and return the desired results.



          In this case you have




          • the array of items to split.

          • The number of days old to split the data, eg 1,2,and 7 days.


          Thus we can have something like the following. The function is declared inside another so that all it needs is safely encapsulated and outside of unrelated scopes.



          const splitByDaysOld = (() => {
          const MS_IN_DAY = 8.64e7;
          const sorter = (a, b) => a - b;
          return function(array, periods) {
          const now = Date.now();
          var start = 0;
          return periods.sort(sorter).map(day => {
          const res = array.filter(item => {
          const daysOld = (item.date - now) / MS_IN_DAY;
          return daysOld >= start && daysOld < day;
          });
          start = day;
          return res;
          });
          };
          })();


          It returns an array of arrays, one for each period.



          Example below has 3 periods 0 to < 1, 1 to < 2, and 2 to < 7 days old.



          const [today, yesterday, week] = splitByDaysOld(arr, [1, 2, 7]);


          Note that the periods array is sorted from most recent to oldest and that the result will be in the same order







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 11 hours ago









          Blindman67Blindman67

          8,1951521




          8,1951521












          • $begingroup$
            The function is called listAllPercos and it exists. So yes, it is just an example. Didn't think about making it like this though. Question totally out of context, but is this considerd a factory ? And I'm going to try to implement it with what I need and don't, and keep you updated. Anyway, have my upvote too !
            $endgroup$
            – trichetriche
            10 hours ago


















          • $begingroup$
            The function is called listAllPercos and it exists. So yes, it is just an example. Didn't think about making it like this though. Question totally out of context, but is this considerd a factory ? And I'm going to try to implement it with what I need and don't, and keep you updated. Anyway, have my upvote too !
            $endgroup$
            – trichetriche
            10 hours ago
















          $begingroup$
          The function is called listAllPercos and it exists. So yes, it is just an example. Didn't think about making it like this though. Question totally out of context, but is this considerd a factory ? And I'm going to try to implement it with what I need and don't, and keep you updated. Anyway, have my upvote too !
          $endgroup$
          – trichetriche
          10 hours ago




          $begingroup$
          The function is called listAllPercos and it exists. So yes, it is just an example. Didn't think about making it like this though. Question totally out of context, but is this considerd a factory ? And I'm going to try to implement it with what I need and don't, and keep you updated. Anyway, have my upvote too !
          $endgroup$
          – trichetriche
          10 hours ago










          trichetriche is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          trichetriche is a new contributor. Be nice, and check out our Code of Conduct.













          trichetriche is a new contributor. Be nice, and check out our Code of Conduct.












          trichetriche is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • 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.


          Use MathJax to format equations. MathJax reference.


          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%2fcodereview.stackexchange.com%2fquestions%2f214540%2fsplit-an-array-of-items-into-several-arrays-given-a-condition%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

          is 'sed' thread safeWhat should someone know about using Python scripts in the shell?Nexenta bash script uses...

          How do i solve the “ No module named 'mlxtend' ” issue on Jupyter?

          Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...