Can I increase the index of map() by 2?












1














I have a problem with converting the array to object.



const data = [0, 1, 2, 3, 4, 5];
const arr = data.map((element, idx) => {
return {
f: element,
s: arr[idx + 1],
};
});


Of course, arr is [{f: 0, s: 1}, {f: 1, s: 2}, ...], but I want to increase the index of map by 2. The result will like this:



arr = [{ f: 0, s: 1}, { f: 2, s: 3 }, ...]


Is there any way to make the result using method likes map?










share|improve this question


















  • 1




    I think you'll have to use another loop (forEach, or traditional for loop) and keep track of a secondary index yourself
    – duxfox--
    Nov 20 at 2:14










  • Maybe use reduce instead.
    – Dominique Fortin
    Nov 20 at 2:16
















1














I have a problem with converting the array to object.



const data = [0, 1, 2, 3, 4, 5];
const arr = data.map((element, idx) => {
return {
f: element,
s: arr[idx + 1],
};
});


Of course, arr is [{f: 0, s: 1}, {f: 1, s: 2}, ...], but I want to increase the index of map by 2. The result will like this:



arr = [{ f: 0, s: 1}, { f: 2, s: 3 }, ...]


Is there any way to make the result using method likes map?










share|improve this question


















  • 1




    I think you'll have to use another loop (forEach, or traditional for loop) and keep track of a secondary index yourself
    – duxfox--
    Nov 20 at 2:14










  • Maybe use reduce instead.
    – Dominique Fortin
    Nov 20 at 2:16














1












1








1







I have a problem with converting the array to object.



const data = [0, 1, 2, 3, 4, 5];
const arr = data.map((element, idx) => {
return {
f: element,
s: arr[idx + 1],
};
});


Of course, arr is [{f: 0, s: 1}, {f: 1, s: 2}, ...], but I want to increase the index of map by 2. The result will like this:



arr = [{ f: 0, s: 1}, { f: 2, s: 3 }, ...]


Is there any way to make the result using method likes map?










share|improve this question













I have a problem with converting the array to object.



const data = [0, 1, 2, 3, 4, 5];
const arr = data.map((element, idx) => {
return {
f: element,
s: arr[idx + 1],
};
});


Of course, arr is [{f: 0, s: 1}, {f: 1, s: 2}, ...], but I want to increase the index of map by 2. The result will like this:



arr = [{ f: 0, s: 1}, { f: 2, s: 3 }, ...]


Is there any way to make the result using method likes map?







javascript arrays functional-programming






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 2:11









Caesium133

5619




5619








  • 1




    I think you'll have to use another loop (forEach, or traditional for loop) and keep track of a secondary index yourself
    – duxfox--
    Nov 20 at 2:14










  • Maybe use reduce instead.
    – Dominique Fortin
    Nov 20 at 2:16














  • 1




    I think you'll have to use another loop (forEach, or traditional for loop) and keep track of a secondary index yourself
    – duxfox--
    Nov 20 at 2:14










  • Maybe use reduce instead.
    – Dominique Fortin
    Nov 20 at 2:16








1




1




I think you'll have to use another loop (forEach, or traditional for loop) and keep track of a secondary index yourself
– duxfox--
Nov 20 at 2:14




I think you'll have to use another loop (forEach, or traditional for loop) and keep track of a secondary index yourself
– duxfox--
Nov 20 at 2:14












Maybe use reduce instead.
– Dominique Fortin
Nov 20 at 2:16




Maybe use reduce instead.
– Dominique Fortin
Nov 20 at 2:16












2 Answers
2






active

oldest

votes


















4














You could do this with Array.reduce if I understood your question correctly:






const data = [0, 1, 2, 3, 4, 5];
const result = data.reduce((r,c,i,a) => {
if(i%2 == 0)
r.push({ f: i, s: a[i+1] })
return r
}, );

console.log(result)





The idea is to use the % operator in combination with the reduce to push only the values you would want into the accumulator array.



Doing this with map would be trickier since map goes through every element and expects the same number of elements out as they ware in where the reduce can have any result type/length specified by the accumulator.






share|improve this answer































    0














    You can do pretty much anything with reduce, but it’s a bad fit for this:



    arr = data.reduce( ( acc, item, i ) => {
    if ( i % 2 === 0 ) {
    acc[ acc.length - 1 ].s = item
    } else {
    acc.push({ f: item })
    }
    return acc
    }, )


    Better to split the array with a good old for loop, then map that:



    var pairwise = arr => {
    var pairs =
    for ( var i = 0; i < arr.length; i++ ) {
    pairs.push([ arr[ i ], arr[ i + 1 ] ])
    }
    return pairs
    }

    arr = pairwise( data ).map( ([ f, s ]) => ({ f, s }) )





    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%2f53385244%2fcan-i-increase-the-index-of-map-by-2%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









      4














      You could do this with Array.reduce if I understood your question correctly:






      const data = [0, 1, 2, 3, 4, 5];
      const result = data.reduce((r,c,i,a) => {
      if(i%2 == 0)
      r.push({ f: i, s: a[i+1] })
      return r
      }, );

      console.log(result)





      The idea is to use the % operator in combination with the reduce to push only the values you would want into the accumulator array.



      Doing this with map would be trickier since map goes through every element and expects the same number of elements out as they ware in where the reduce can have any result type/length specified by the accumulator.






      share|improve this answer




























        4














        You could do this with Array.reduce if I understood your question correctly:






        const data = [0, 1, 2, 3, 4, 5];
        const result = data.reduce((r,c,i,a) => {
        if(i%2 == 0)
        r.push({ f: i, s: a[i+1] })
        return r
        }, );

        console.log(result)





        The idea is to use the % operator in combination with the reduce to push only the values you would want into the accumulator array.



        Doing this with map would be trickier since map goes through every element and expects the same number of elements out as they ware in where the reduce can have any result type/length specified by the accumulator.






        share|improve this answer


























          4












          4








          4






          You could do this with Array.reduce if I understood your question correctly:






          const data = [0, 1, 2, 3, 4, 5];
          const result = data.reduce((r,c,i,a) => {
          if(i%2 == 0)
          r.push({ f: i, s: a[i+1] })
          return r
          }, );

          console.log(result)





          The idea is to use the % operator in combination with the reduce to push only the values you would want into the accumulator array.



          Doing this with map would be trickier since map goes through every element and expects the same number of elements out as they ware in where the reduce can have any result type/length specified by the accumulator.






          share|improve this answer














          You could do this with Array.reduce if I understood your question correctly:






          const data = [0, 1, 2, 3, 4, 5];
          const result = data.reduce((r,c,i,a) => {
          if(i%2 == 0)
          r.push({ f: i, s: a[i+1] })
          return r
          }, );

          console.log(result)





          The idea is to use the % operator in combination with the reduce to push only the values you would want into the accumulator array.



          Doing this with map would be trickier since map goes through every element and expects the same number of elements out as they ware in where the reduce can have any result type/length specified by the accumulator.






          const data = [0, 1, 2, 3, 4, 5];
          const result = data.reduce((r,c,i,a) => {
          if(i%2 == 0)
          r.push({ f: i, s: a[i+1] })
          return r
          }, );

          console.log(result)





          const data = [0, 1, 2, 3, 4, 5];
          const result = data.reduce((r,c,i,a) => {
          if(i%2 == 0)
          r.push({ f: i, s: a[i+1] })
          return r
          }, );

          console.log(result)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 at 2:33

























          answered Nov 20 at 2:17









          Akrion

          9,37211224




          9,37211224

























              0














              You can do pretty much anything with reduce, but it’s a bad fit for this:



              arr = data.reduce( ( acc, item, i ) => {
              if ( i % 2 === 0 ) {
              acc[ acc.length - 1 ].s = item
              } else {
              acc.push({ f: item })
              }
              return acc
              }, )


              Better to split the array with a good old for loop, then map that:



              var pairwise = arr => {
              var pairs =
              for ( var i = 0; i < arr.length; i++ ) {
              pairs.push([ arr[ i ], arr[ i + 1 ] ])
              }
              return pairs
              }

              arr = pairwise( data ).map( ([ f, s ]) => ({ f, s }) )





              share|improve this answer




























                0














                You can do pretty much anything with reduce, but it’s a bad fit for this:



                arr = data.reduce( ( acc, item, i ) => {
                if ( i % 2 === 0 ) {
                acc[ acc.length - 1 ].s = item
                } else {
                acc.push({ f: item })
                }
                return acc
                }, )


                Better to split the array with a good old for loop, then map that:



                var pairwise = arr => {
                var pairs =
                for ( var i = 0; i < arr.length; i++ ) {
                pairs.push([ arr[ i ], arr[ i + 1 ] ])
                }
                return pairs
                }

                arr = pairwise( data ).map( ([ f, s ]) => ({ f, s }) )





                share|improve this answer


























                  0












                  0








                  0






                  You can do pretty much anything with reduce, but it’s a bad fit for this:



                  arr = data.reduce( ( acc, item, i ) => {
                  if ( i % 2 === 0 ) {
                  acc[ acc.length - 1 ].s = item
                  } else {
                  acc.push({ f: item })
                  }
                  return acc
                  }, )


                  Better to split the array with a good old for loop, then map that:



                  var pairwise = arr => {
                  var pairs =
                  for ( var i = 0; i < arr.length; i++ ) {
                  pairs.push([ arr[ i ], arr[ i + 1 ] ])
                  }
                  return pairs
                  }

                  arr = pairwise( data ).map( ([ f, s ]) => ({ f, s }) )





                  share|improve this answer














                  You can do pretty much anything with reduce, but it’s a bad fit for this:



                  arr = data.reduce( ( acc, item, i ) => {
                  if ( i % 2 === 0 ) {
                  acc[ acc.length - 1 ].s = item
                  } else {
                  acc.push({ f: item })
                  }
                  return acc
                  }, )


                  Better to split the array with a good old for loop, then map that:



                  var pairwise = arr => {
                  var pairs =
                  for ( var i = 0; i < arr.length; i++ ) {
                  pairs.push([ arr[ i ], arr[ i + 1 ] ])
                  }
                  return pairs
                  }

                  arr = pairwise( data ).map( ([ f, s ]) => ({ f, s }) )






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 20 at 2:36









                  Mark Meyer

                  35k32855




                  35k32855










                  answered Nov 20 at 2:27









                  Ben West

                  2,6611814




                  2,6611814






























                      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.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • 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%2f53385244%2fcan-i-increase-the-index-of-map-by-2%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

                      Paul Cézanne

                      UIScrollView CustomStickyHeader Resize height generates problems when scroll is too fast

                      Angular material date-picker (MatDatepicker) auto completes the date on focus out