JavaScript inline function to array map











up vote
1
down vote

favorite
1












Is it possibile to use an inline return with javascript map function?
Instead of doing



array.map(token => { var x=new Object(); x[token]=words[token]; return x;} )


I would like to do it inline as doing



array.map(token => token )


so applying a inline method like



array.map(token => inline_function(token) )


I have tried like



Object.keys(chart).sort((a,b) => words[b]-words[a]).map(token => ( (token) => (new Object())[token]=words[token] )(token) )


but cannot get the return using a anonymous call with ().



Here is an example using the non inline case:






text = "Lorem ipsum dolor sit amet,n consectetur adipiscing elit,nsed do eiusmod tempor incididuntnut labore et dolore magna aliqua.nUt enim ad minim veniam,nquis nostrud exercitation ullamco laboris nisinut aliquip ex ea commodo consequat.nDuis aute irure dolor in reprehenderit in voluptate velit essencillum dolore eu fugiat nulla pariatur.nExcepteur sint occaecat cupidatat non proident,nLorem ipsum dolor sit amet etwas,nsunt in culpa qui officia deserunt mollit anim id est laborum"

words = text.split(/s+/g)

count = words.reduce(function(m, v) {
m[v] = m[v] ? m[v] + 1 : 1;
return m;
}, {})

sorted = Object.keys(count).sort((a, b) => count[b] - count[a]).map(token => {
var x = new Object();
x[token] = count[token];
return x;
})

console.log(sorted)












share|improve this question


























    up vote
    1
    down vote

    favorite
    1












    Is it possibile to use an inline return with javascript map function?
    Instead of doing



    array.map(token => { var x=new Object(); x[token]=words[token]; return x;} )


    I would like to do it inline as doing



    array.map(token => token )


    so applying a inline method like



    array.map(token => inline_function(token) )


    I have tried like



    Object.keys(chart).sort((a,b) => words[b]-words[a]).map(token => ( (token) => (new Object())[token]=words[token] )(token) )


    but cannot get the return using a anonymous call with ().



    Here is an example using the non inline case:






    text = "Lorem ipsum dolor sit amet,n consectetur adipiscing elit,nsed do eiusmod tempor incididuntnut labore et dolore magna aliqua.nUt enim ad minim veniam,nquis nostrud exercitation ullamco laboris nisinut aliquip ex ea commodo consequat.nDuis aute irure dolor in reprehenderit in voluptate velit essencillum dolore eu fugiat nulla pariatur.nExcepteur sint occaecat cupidatat non proident,nLorem ipsum dolor sit amet etwas,nsunt in culpa qui officia deserunt mollit anim id est laborum"

    words = text.split(/s+/g)

    count = words.reduce(function(m, v) {
    m[v] = m[v] ? m[v] + 1 : 1;
    return m;
    }, {})

    sorted = Object.keys(count).sort((a, b) => count[b] - count[a]).map(token => {
    var x = new Object();
    x[token] = count[token];
    return x;
    })

    console.log(sorted)












    share|improve this question
























      up vote
      1
      down vote

      favorite
      1









      up vote
      1
      down vote

      favorite
      1






      1





      Is it possibile to use an inline return with javascript map function?
      Instead of doing



      array.map(token => { var x=new Object(); x[token]=words[token]; return x;} )


      I would like to do it inline as doing



      array.map(token => token )


      so applying a inline method like



      array.map(token => inline_function(token) )


      I have tried like



      Object.keys(chart).sort((a,b) => words[b]-words[a]).map(token => ( (token) => (new Object())[token]=words[token] )(token) )


      but cannot get the return using a anonymous call with ().



      Here is an example using the non inline case:






      text = "Lorem ipsum dolor sit amet,n consectetur adipiscing elit,nsed do eiusmod tempor incididuntnut labore et dolore magna aliqua.nUt enim ad minim veniam,nquis nostrud exercitation ullamco laboris nisinut aliquip ex ea commodo consequat.nDuis aute irure dolor in reprehenderit in voluptate velit essencillum dolore eu fugiat nulla pariatur.nExcepteur sint occaecat cupidatat non proident,nLorem ipsum dolor sit amet etwas,nsunt in culpa qui officia deserunt mollit anim id est laborum"

      words = text.split(/s+/g)

      count = words.reduce(function(m, v) {
      m[v] = m[v] ? m[v] + 1 : 1;
      return m;
      }, {})

      sorted = Object.keys(count).sort((a, b) => count[b] - count[a]).map(token => {
      var x = new Object();
      x[token] = count[token];
      return x;
      })

      console.log(sorted)












      share|improve this question













      Is it possibile to use an inline return with javascript map function?
      Instead of doing



      array.map(token => { var x=new Object(); x[token]=words[token]; return x;} )


      I would like to do it inline as doing



      array.map(token => token )


      so applying a inline method like



      array.map(token => inline_function(token) )


      I have tried like



      Object.keys(chart).sort((a,b) => words[b]-words[a]).map(token => ( (token) => (new Object())[token]=words[token] )(token) )


      but cannot get the return using a anonymous call with ().



      Here is an example using the non inline case:






      text = "Lorem ipsum dolor sit amet,n consectetur adipiscing elit,nsed do eiusmod tempor incididuntnut labore et dolore magna aliqua.nUt enim ad minim veniam,nquis nostrud exercitation ullamco laboris nisinut aliquip ex ea commodo consequat.nDuis aute irure dolor in reprehenderit in voluptate velit essencillum dolore eu fugiat nulla pariatur.nExcepteur sint occaecat cupidatat non proident,nLorem ipsum dolor sit amet etwas,nsunt in culpa qui officia deserunt mollit anim id est laborum"

      words = text.split(/s+/g)

      count = words.reduce(function(m, v) {
      m[v] = m[v] ? m[v] + 1 : 1;
      return m;
      }, {})

      sorted = Object.keys(count).sort((a, b) => count[b] - count[a]).map(token => {
      var x = new Object();
      x[token] = count[token];
      return x;
      })

      console.log(sorted)








      text = "Lorem ipsum dolor sit amet,n consectetur adipiscing elit,nsed do eiusmod tempor incididuntnut labore et dolore magna aliqua.nUt enim ad minim veniam,nquis nostrud exercitation ullamco laboris nisinut aliquip ex ea commodo consequat.nDuis aute irure dolor in reprehenderit in voluptate velit essencillum dolore eu fugiat nulla pariatur.nExcepteur sint occaecat cupidatat non proident,nLorem ipsum dolor sit amet etwas,nsunt in culpa qui officia deserunt mollit anim id est laborum"

      words = text.split(/s+/g)

      count = words.reduce(function(m, v) {
      m[v] = m[v] ? m[v] + 1 : 1;
      return m;
      }, {})

      sorted = Object.keys(count).sort((a, b) => count[b] - count[a]).map(token => {
      var x = new Object();
      x[token] = count[token];
      return x;
      })

      console.log(sorted)





      text = "Lorem ipsum dolor sit amet,n consectetur adipiscing elit,nsed do eiusmod tempor incididuntnut labore et dolore magna aliqua.nUt enim ad minim veniam,nquis nostrud exercitation ullamco laboris nisinut aliquip ex ea commodo consequat.nDuis aute irure dolor in reprehenderit in voluptate velit essencillum dolore eu fugiat nulla pariatur.nExcepteur sint occaecat cupidatat non proident,nLorem ipsum dolor sit amet etwas,nsunt in culpa qui officia deserunt mollit anim id est laborum"

      words = text.split(/s+/g)

      count = words.reduce(function(m, v) {
      m[v] = m[v] ? m[v] + 1 : 1;
      return m;
      }, {})

      sorted = Object.keys(count).sort((a, b) => count[b] - count[a]).map(token => {
      var x = new Object();
      x[token] = count[token];
      return x;
      })

      console.log(sorted)






      javascript arrays






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 14:26









      loretoparisi

      7,55754771




      7,55754771
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          All of those are inline functions. Fundamentally, you're asking how to write this callback:



          token => {
          var x = new Object();
          x[token] = count[token];
          return x;
          }


          with a concise body rather than a function body. In this specific case, you can do that with a computed property name:



          token => ({[token]: count[token]})
          // ^^^^^^^---- computed property name, new in ES2015


          Note we need the parens (()) around the concise body because the first character of it would be { (the beginning of the object initializer) otherwise, which would make the parser think it had a function body rather than a concise one.



          In the more general case, you can't turn a function body into a concise body unless everything fits within a single expression, such as the object initializer above. Sometimes you can use (or arguably abuse) the comma operator for that, with the left-hand operand to , having side-effects, but in such cases it's usually clearer to just leave the function body instead.



          As an example of that (ab)use, this logs the values prior to doubling them:



          doubled = values.map(v => (console.log(v), v * 2));


          I don't recommend it, but you'll see it done. :-)






          share|improve this answer



















          • 1




            Beat me to it by 2 seconds! :)
            – ibrahim mahrir
            Nov 12 at 14:32






          • 2




            @ibrahimmahrir - But perhaps you wouldn't have had the silly typo (= instead of :). Fixed now. :-)
            – T.J. Crowder
            Nov 12 at 14:34










          • amazing I missed the computed property. Thanks T.J. ;)
            – loretoparisi
            Nov 12 at 14:35


















          up vote
          2
          down vote













          Why not pass a function to .map?



          function myFunction(token){
          var x = new Object();
          x[token] = count[token];
          return x;
          }

          sorted = Object.keys(count).sort((a, b) => count[b] - count[a]).map(myFunction);





          share|improve this answer





















          • Yes that is correct. I was trying to understand if I can infer () to inline function call like like (() => something))()
            – loretoparisi
            Nov 12 at 14:31






          • 1




            @loretoparisi Ah, apologies. I must of misunderstood what you're asking.
            – Adriani6
            Nov 12 at 14:32











          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',
          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%2f53264233%2fjavascript-inline-function-to-array-map%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








          up vote
          3
          down vote



          accepted










          All of those are inline functions. Fundamentally, you're asking how to write this callback:



          token => {
          var x = new Object();
          x[token] = count[token];
          return x;
          }


          with a concise body rather than a function body. In this specific case, you can do that with a computed property name:



          token => ({[token]: count[token]})
          // ^^^^^^^---- computed property name, new in ES2015


          Note we need the parens (()) around the concise body because the first character of it would be { (the beginning of the object initializer) otherwise, which would make the parser think it had a function body rather than a concise one.



          In the more general case, you can't turn a function body into a concise body unless everything fits within a single expression, such as the object initializer above. Sometimes you can use (or arguably abuse) the comma operator for that, with the left-hand operand to , having side-effects, but in such cases it's usually clearer to just leave the function body instead.



          As an example of that (ab)use, this logs the values prior to doubling them:



          doubled = values.map(v => (console.log(v), v * 2));


          I don't recommend it, but you'll see it done. :-)






          share|improve this answer



















          • 1




            Beat me to it by 2 seconds! :)
            – ibrahim mahrir
            Nov 12 at 14:32






          • 2




            @ibrahimmahrir - But perhaps you wouldn't have had the silly typo (= instead of :). Fixed now. :-)
            – T.J. Crowder
            Nov 12 at 14:34










          • amazing I missed the computed property. Thanks T.J. ;)
            – loretoparisi
            Nov 12 at 14:35















          up vote
          3
          down vote



          accepted










          All of those are inline functions. Fundamentally, you're asking how to write this callback:



          token => {
          var x = new Object();
          x[token] = count[token];
          return x;
          }


          with a concise body rather than a function body. In this specific case, you can do that with a computed property name:



          token => ({[token]: count[token]})
          // ^^^^^^^---- computed property name, new in ES2015


          Note we need the parens (()) around the concise body because the first character of it would be { (the beginning of the object initializer) otherwise, which would make the parser think it had a function body rather than a concise one.



          In the more general case, you can't turn a function body into a concise body unless everything fits within a single expression, such as the object initializer above. Sometimes you can use (or arguably abuse) the comma operator for that, with the left-hand operand to , having side-effects, but in such cases it's usually clearer to just leave the function body instead.



          As an example of that (ab)use, this logs the values prior to doubling them:



          doubled = values.map(v => (console.log(v), v * 2));


          I don't recommend it, but you'll see it done. :-)






          share|improve this answer



















          • 1




            Beat me to it by 2 seconds! :)
            – ibrahim mahrir
            Nov 12 at 14:32






          • 2




            @ibrahimmahrir - But perhaps you wouldn't have had the silly typo (= instead of :). Fixed now. :-)
            – T.J. Crowder
            Nov 12 at 14:34










          • amazing I missed the computed property. Thanks T.J. ;)
            – loretoparisi
            Nov 12 at 14:35













          up vote
          3
          down vote



          accepted







          up vote
          3
          down vote



          accepted






          All of those are inline functions. Fundamentally, you're asking how to write this callback:



          token => {
          var x = new Object();
          x[token] = count[token];
          return x;
          }


          with a concise body rather than a function body. In this specific case, you can do that with a computed property name:



          token => ({[token]: count[token]})
          // ^^^^^^^---- computed property name, new in ES2015


          Note we need the parens (()) around the concise body because the first character of it would be { (the beginning of the object initializer) otherwise, which would make the parser think it had a function body rather than a concise one.



          In the more general case, you can't turn a function body into a concise body unless everything fits within a single expression, such as the object initializer above. Sometimes you can use (or arguably abuse) the comma operator for that, with the left-hand operand to , having side-effects, but in such cases it's usually clearer to just leave the function body instead.



          As an example of that (ab)use, this logs the values prior to doubling them:



          doubled = values.map(v => (console.log(v), v * 2));


          I don't recommend it, but you'll see it done. :-)






          share|improve this answer














          All of those are inline functions. Fundamentally, you're asking how to write this callback:



          token => {
          var x = new Object();
          x[token] = count[token];
          return x;
          }


          with a concise body rather than a function body. In this specific case, you can do that with a computed property name:



          token => ({[token]: count[token]})
          // ^^^^^^^---- computed property name, new in ES2015


          Note we need the parens (()) around the concise body because the first character of it would be { (the beginning of the object initializer) otherwise, which would make the parser think it had a function body rather than a concise one.



          In the more general case, you can't turn a function body into a concise body unless everything fits within a single expression, such as the object initializer above. Sometimes you can use (or arguably abuse) the comma operator for that, with the left-hand operand to , having side-effects, but in such cases it's usually clearer to just leave the function body instead.



          As an example of that (ab)use, this logs the values prior to doubling them:



          doubled = values.map(v => (console.log(v), v * 2));


          I don't recommend it, but you'll see it done. :-)







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 12 at 14:36

























          answered Nov 12 at 14:31









          T.J. Crowder

          674k11811911287




          674k11811911287








          • 1




            Beat me to it by 2 seconds! :)
            – ibrahim mahrir
            Nov 12 at 14:32






          • 2




            @ibrahimmahrir - But perhaps you wouldn't have had the silly typo (= instead of :). Fixed now. :-)
            – T.J. Crowder
            Nov 12 at 14:34










          • amazing I missed the computed property. Thanks T.J. ;)
            – loretoparisi
            Nov 12 at 14:35














          • 1




            Beat me to it by 2 seconds! :)
            – ibrahim mahrir
            Nov 12 at 14:32






          • 2




            @ibrahimmahrir - But perhaps you wouldn't have had the silly typo (= instead of :). Fixed now. :-)
            – T.J. Crowder
            Nov 12 at 14:34










          • amazing I missed the computed property. Thanks T.J. ;)
            – loretoparisi
            Nov 12 at 14:35








          1




          1




          Beat me to it by 2 seconds! :)
          – ibrahim mahrir
          Nov 12 at 14:32




          Beat me to it by 2 seconds! :)
          – ibrahim mahrir
          Nov 12 at 14:32




          2




          2




          @ibrahimmahrir - But perhaps you wouldn't have had the silly typo (= instead of :). Fixed now. :-)
          – T.J. Crowder
          Nov 12 at 14:34




          @ibrahimmahrir - But perhaps you wouldn't have had the silly typo (= instead of :). Fixed now. :-)
          – T.J. Crowder
          Nov 12 at 14:34












          amazing I missed the computed property. Thanks T.J. ;)
          – loretoparisi
          Nov 12 at 14:35




          amazing I missed the computed property. Thanks T.J. ;)
          – loretoparisi
          Nov 12 at 14:35












          up vote
          2
          down vote













          Why not pass a function to .map?



          function myFunction(token){
          var x = new Object();
          x[token] = count[token];
          return x;
          }

          sorted = Object.keys(count).sort((a, b) => count[b] - count[a]).map(myFunction);





          share|improve this answer





















          • Yes that is correct. I was trying to understand if I can infer () to inline function call like like (() => something))()
            – loretoparisi
            Nov 12 at 14:31






          • 1




            @loretoparisi Ah, apologies. I must of misunderstood what you're asking.
            – Adriani6
            Nov 12 at 14:32















          up vote
          2
          down vote













          Why not pass a function to .map?



          function myFunction(token){
          var x = new Object();
          x[token] = count[token];
          return x;
          }

          sorted = Object.keys(count).sort((a, b) => count[b] - count[a]).map(myFunction);





          share|improve this answer





















          • Yes that is correct. I was trying to understand if I can infer () to inline function call like like (() => something))()
            – loretoparisi
            Nov 12 at 14:31






          • 1




            @loretoparisi Ah, apologies. I must of misunderstood what you're asking.
            – Adriani6
            Nov 12 at 14:32













          up vote
          2
          down vote










          up vote
          2
          down vote









          Why not pass a function to .map?



          function myFunction(token){
          var x = new Object();
          x[token] = count[token];
          return x;
          }

          sorted = Object.keys(count).sort((a, b) => count[b] - count[a]).map(myFunction);





          share|improve this answer












          Why not pass a function to .map?



          function myFunction(token){
          var x = new Object();
          x[token] = count[token];
          return x;
          }

          sorted = Object.keys(count).sort((a, b) => count[b] - count[a]).map(myFunction);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 12 at 14:30









          Adriani6

          4,05021123




          4,05021123












          • Yes that is correct. I was trying to understand if I can infer () to inline function call like like (() => something))()
            – loretoparisi
            Nov 12 at 14:31






          • 1




            @loretoparisi Ah, apologies. I must of misunderstood what you're asking.
            – Adriani6
            Nov 12 at 14:32


















          • Yes that is correct. I was trying to understand if I can infer () to inline function call like like (() => something))()
            – loretoparisi
            Nov 12 at 14:31






          • 1




            @loretoparisi Ah, apologies. I must of misunderstood what you're asking.
            – Adriani6
            Nov 12 at 14:32
















          Yes that is correct. I was trying to understand if I can infer () to inline function call like like (() => something))()
          – loretoparisi
          Nov 12 at 14:31




          Yes that is correct. I was trying to understand if I can infer () to inline function call like like (() => something))()
          – loretoparisi
          Nov 12 at 14:31




          1




          1




          @loretoparisi Ah, apologies. I must of misunderstood what you're asking.
          – Adriani6
          Nov 12 at 14:32




          @loretoparisi Ah, apologies. I must of misunderstood what you're asking.
          – Adriani6
          Nov 12 at 14:32


















          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%2f53264233%2fjavascript-inline-function-to-array-map%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

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)