looping through javascript object without sorting based on keysWhat is the most efficient way to deep clone an object in JavaScript?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?How do I loop through or enumerate a JavaScript object?How do I correctly clone a JavaScript object?JavaScript closure inside loops – simple practical exampleHow to loop through a plain JavaScript object with the objects as members?Checking if a key exists in a JavaScript object?Loop through an array in JavaScriptIterate through object properties

Is my router's IP address really public?

1960s sci-fi novella with a character who is treated as invisible by being ignored

What are the problems in teaching guitar via Skype?

Is a post-climate apocolypse city in which many or most insects have disappeared realistic?

How were these pictures of spacecraft wind tunnel testing taken?

Do firearms count as ranged weapons?

Can a Beholder use rays in melee range?

Ticket sales for Queen at the Live Aid

Uses of T extends U?

Would an object launched by the Catapult spell do full damage against a Scarecrow?

Mother abusing my finances

Could IPv6 make NAT / port numbers redundant?

How is character development a major role in the plot of a story

Glitch in AC sine wave interfering with phase cut dimming

Where did the “Vikings wear helmets with horn” stereotype come from and why?

Why does the 6502 have the BIT instruction?

Why do Russians call their women expensive ("дорогая")?

What does it mean when you think without speaking?

Tic-Tac-Toe for the terminal

What is the best linguistic term for describing the kw > p / gw > b change, and its usual companion s > h

Split polygon using another polygon in QGIS

Question about exercise 11.5 in TeXbook

Were pen cap holes designed to prevent death by suffocation if swallowed?

Compact Mechanical Energy Source



looping through javascript object without sorting based on keys


What is the most efficient way to deep clone an object in JavaScript?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?How do I loop through or enumerate a JavaScript object?How do I correctly clone a JavaScript object?JavaScript closure inside loops – simple practical exampleHow to loop through a plain JavaScript object with the objects as members?Checking if a key exists in a JavaScript object?Loop through an array in JavaScriptIterate through object properties






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















this is the problem description:
Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.
for example given the array arr=[1,1,0,-1,-1] output should be:



0.400000
0.400000
0.200000


I know there is more more simple solution for it ,and i am sorry for my silly simple question but i wanna make my code work, my code sorts the output based on the key and removes duplicates. for this arr, my code output is:



0.200000
0.400000


thank you so much in advance for any help.



function plusMinus(arr) 
var freq = ;
for (var i = 0; i < arr.length; i++)
if (freq[arr[i]])
freq[arr[i]]++;
else
freq[arr[i]] = 1;

for(var key in freq)

console.log((freq[key]/arr.length).toFixed(6));











share|improve this question






























    1















    this is the problem description:
    Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.
    for example given the array arr=[1,1,0,-1,-1] output should be:



    0.400000
    0.400000
    0.200000


    I know there is more more simple solution for it ,and i am sorry for my silly simple question but i wanna make my code work, my code sorts the output based on the key and removes duplicates. for this arr, my code output is:



    0.200000
    0.400000


    thank you so much in advance for any help.



    function plusMinus(arr) 
    var freq = ;
    for (var i = 0; i < arr.length; i++)
    if (freq[arr[i]])
    freq[arr[i]]++;
    else
    freq[arr[i]] = 1;

    for(var key in freq)

    console.log((freq[key]/arr.length).toFixed(6));











    share|improve this question


























      1












      1








      1








      this is the problem description:
      Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.
      for example given the array arr=[1,1,0,-1,-1] output should be:



      0.400000
      0.400000
      0.200000


      I know there is more more simple solution for it ,and i am sorry for my silly simple question but i wanna make my code work, my code sorts the output based on the key and removes duplicates. for this arr, my code output is:



      0.200000
      0.400000


      thank you so much in advance for any help.



      function plusMinus(arr) 
      var freq = ;
      for (var i = 0; i < arr.length; i++)
      if (freq[arr[i]])
      freq[arr[i]]++;
      else
      freq[arr[i]] = 1;

      for(var key in freq)

      console.log((freq[key]/arr.length).toFixed(6));











      share|improve this question
















      this is the problem description:
      Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.
      for example given the array arr=[1,1,0,-1,-1] output should be:



      0.400000
      0.400000
      0.200000


      I know there is more more simple solution for it ,and i am sorry for my silly simple question but i wanna make my code work, my code sorts the output based on the key and removes duplicates. for this arr, my code output is:



      0.200000
      0.400000


      thank you so much in advance for any help.



      function plusMinus(arr) 
      var freq = ;
      for (var i = 0; i < arr.length; i++)
      if (freq[arr[i]])
      freq[arr[i]]++;
      else
      freq[arr[i]] = 1;

      for(var key in freq)

      console.log((freq[key]/arr.length).toFixed(6));








      javascript object






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 24 at 10:30







      eng

















      asked Mar 24 at 8:55









      engeng

      255




      255






















          7 Answers
          7






          active

          oldest

          votes


















          0














          Let's make sure the order of key in the map by defining it first.






          function plusMinus(arr) 
          var freq =
          posetive: 0,
          negative: 0,
          zero: 0
          ;
          for (var i = 0; i < arr.length; i++)
          if( arr[i] < 0)
          freq.negative++;
          else if(arr[i] > 0)
          freq.posetive++;
          else
          freq.zero++;


          for(var key in freq)
          console.log((freq[key]/arr.length).toFixed(6));


          plusMinus([1,1,0,-1,-1]);








          share|improve this answer






























            2














            You could take an object with predifined properties, this prevents each loop for checking the existence and take an array of keys for getting the result in a wanted order.






            function plusMinus(arr) 
            var freq = 1: 0, '-1': 0, 0: 0 ,
            i, key;

            for (i = 0; i < arr.length; i++)
            freq[arr[i]]++;


            for (key of [1, -1, 0])
            console.log((freq[key] / arr.length).toFixed(6));



            plusMinus([1, 1, 0, -1, -1]);








            share|improve this answer


















            • 1





              The number can be any integer according the question. You might have to do: freq[Math.sign(arr[i])]++

              – adiga
              Mar 24 at 9:47












            • @adiga, right, for any integer, the sign sould be sufficient.

              – Nina Scholz
              Mar 24 at 9:49











            • @NinaScholz the order is right now but still deletes duplicates, the output should be 0.4,0.4,0.2 but its giving 0.4,0.2 , why is that?

              – eng
              Mar 24 at 10:32












            • i don't understand the last output. what do you get?

              – Nina Scholz
              Mar 24 at 10:37











            • @NinaScholz Sorry, it was my mistake. thats right

              – eng
              Mar 24 at 10:52



















            0














            You can use reduce.



            Here idea is



            • First loop through original array and check for the value.

            • If value is zero we increment count of zero key.

            • If value is positive we increment count of pos key.

            • If value is negative we increment count of neg key.

            • Finally we divide each count by length of array.




            let arr = [1,1,0,-1,-1]

            let op = arr.reduce((op,inp)=>
            if(inp === 0)
            op.zero.count++
            else if (inp > 0)
            op.pos.count++;
            else
            op.neg.count++;

            return op
            ,zero:count:0,pos:count:0,neg:count:0)


            let final = Object.entries(op).map(([key,value])=>(
            [key] : value.count / arr.length
            ))

            console.log(final)








            share|improve this answer






























              0














              Use reduce, map and filter:






              const arr = [1, 1, 0, -1, -1];

              const counts = arr.reduce((acc, curr) =>
              if (!curr) acc[0]++;
              else if (curr > 0) acc[1]++;
              else acc[2]++;
              return acc
              , [0, 0, 0]);

              const result = counts.map(e => e / arr.length).filter((e, i, a) => a.indexOf(e) == i);

              console.log(result);








              share|improve this answer






























                0














                You can try using Array.reduce and the resulting array will have the fraction of positive number at the '0'th index, negative at '1'st and zero at the '2'nd index.



                Now if you want to control the count of the number of elements after decimal point, use Array.map at the end to transform it.






                const array = [1,1,0,-1,-1];
                function plusMinus(arr)
                const output = arr.reduce((acc, ele) =>
                if(ele > 0)
                if(ele < 0)
                acc[1] = ((acc[1]
                if(ele === 0) 0 ) + 1 / arr.length);

                return acc;
                , []).map(ele => ele.toFixed(6));
                console.log(...output);

                plusMinus(array);








                share|improve this answer
































                  0














                  Math.sign is your friend here.
                  Math.sign



                  Also lodash would really help this snippet to be cleaner, I highly recommend _.countBy. Lodash .countBy



                  Here's the code.






                  const plusMinus = (numbers) => 
                  // Count by Sign (-1, 0 1)
                  const countSign = _.countBy(numbers, Math.sign);
                  // _.countBy return object, of counted '1': 2, '0': 1, '-1': 2

                  // Print them in orders
                  const printOrder = [1, -1, 0];
                  printOrder.forEach(sign =>
                  console.log((countSign[sign] / numbers.length).toFixed(6));
                  );


                  const testArr = [1,1,0,-1,-1];
                  plusMinus(testArr);

                  <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>








                  share|improve this answer






























                    0














                    Here is another one-line solution using Array.reduce() and Array.forEach() functions:






                    const plusMinus = arr => arr
                    .reduce((res, curr) => ++res[!curr ? 2 : curr < 0 ? 1 : 0] && res, [0, 0, 0])
                    .forEach(i => console.log((i / arr.length).toFixed(6)));

                    plusMinus([1, 1, 0, -1, -1]);








                    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%2f55322117%2flooping-through-javascript-object-without-sorting-based-on-keys%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown

























                      7 Answers
                      7






                      active

                      oldest

                      votes








                      7 Answers
                      7






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      0














                      Let's make sure the order of key in the map by defining it first.






                      function plusMinus(arr) 
                      var freq =
                      posetive: 0,
                      negative: 0,
                      zero: 0
                      ;
                      for (var i = 0; i < arr.length; i++)
                      if( arr[i] < 0)
                      freq.negative++;
                      else if(arr[i] > 0)
                      freq.posetive++;
                      else
                      freq.zero++;


                      for(var key in freq)
                      console.log((freq[key]/arr.length).toFixed(6));


                      plusMinus([1,1,0,-1,-1]);








                      share|improve this answer



























                        0














                        Let's make sure the order of key in the map by defining it first.






                        function plusMinus(arr) 
                        var freq =
                        posetive: 0,
                        negative: 0,
                        zero: 0
                        ;
                        for (var i = 0; i < arr.length; i++)
                        if( arr[i] < 0)
                        freq.negative++;
                        else if(arr[i] > 0)
                        freq.posetive++;
                        else
                        freq.zero++;


                        for(var key in freq)
                        console.log((freq[key]/arr.length).toFixed(6));


                        plusMinus([1,1,0,-1,-1]);








                        share|improve this answer

























                          0












                          0








                          0







                          Let's make sure the order of key in the map by defining it first.






                          function plusMinus(arr) 
                          var freq =
                          posetive: 0,
                          negative: 0,
                          zero: 0
                          ;
                          for (var i = 0; i < arr.length; i++)
                          if( arr[i] < 0)
                          freq.negative++;
                          else if(arr[i] > 0)
                          freq.posetive++;
                          else
                          freq.zero++;


                          for(var key in freq)
                          console.log((freq[key]/arr.length).toFixed(6));


                          plusMinus([1,1,0,-1,-1]);








                          share|improve this answer













                          Let's make sure the order of key in the map by defining it first.






                          function plusMinus(arr) 
                          var freq =
                          posetive: 0,
                          negative: 0,
                          zero: 0
                          ;
                          for (var i = 0; i < arr.length; i++)
                          if( arr[i] < 0)
                          freq.negative++;
                          else if(arr[i] > 0)
                          freq.posetive++;
                          else
                          freq.zero++;


                          for(var key in freq)
                          console.log((freq[key]/arr.length).toFixed(6));


                          plusMinus([1,1,0,-1,-1]);








                          function plusMinus(arr) 
                          var freq =
                          posetive: 0,
                          negative: 0,
                          zero: 0
                          ;
                          for (var i = 0; i < arr.length; i++)
                          if( arr[i] < 0)
                          freq.negative++;
                          else if(arr[i] > 0)
                          freq.posetive++;
                          else
                          freq.zero++;


                          for(var key in freq)
                          console.log((freq[key]/arr.length).toFixed(6));


                          plusMinus([1,1,0,-1,-1]);





                          function plusMinus(arr) 
                          var freq =
                          posetive: 0,
                          negative: 0,
                          zero: 0
                          ;
                          for (var i = 0; i < arr.length; i++)
                          if( arr[i] < 0)
                          freq.negative++;
                          else if(arr[i] > 0)
                          freq.posetive++;
                          else
                          freq.zero++;


                          for(var key in freq)
                          console.log((freq[key]/arr.length).toFixed(6));


                          plusMinus([1,1,0,-1,-1]);






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 24 at 9:11









                          DipakDipak

                          3,18144064




                          3,18144064























                              2














                              You could take an object with predifined properties, this prevents each loop for checking the existence and take an array of keys for getting the result in a wanted order.






                              function plusMinus(arr) 
                              var freq = 1: 0, '-1': 0, 0: 0 ,
                              i, key;

                              for (i = 0; i < arr.length; i++)
                              freq[arr[i]]++;


                              for (key of [1, -1, 0])
                              console.log((freq[key] / arr.length).toFixed(6));



                              plusMinus([1, 1, 0, -1, -1]);








                              share|improve this answer


















                              • 1





                                The number can be any integer according the question. You might have to do: freq[Math.sign(arr[i])]++

                                – adiga
                                Mar 24 at 9:47












                              • @adiga, right, for any integer, the sign sould be sufficient.

                                – Nina Scholz
                                Mar 24 at 9:49











                              • @NinaScholz the order is right now but still deletes duplicates, the output should be 0.4,0.4,0.2 but its giving 0.4,0.2 , why is that?

                                – eng
                                Mar 24 at 10:32












                              • i don't understand the last output. what do you get?

                                – Nina Scholz
                                Mar 24 at 10:37











                              • @NinaScholz Sorry, it was my mistake. thats right

                                – eng
                                Mar 24 at 10:52
















                              2














                              You could take an object with predifined properties, this prevents each loop for checking the existence and take an array of keys for getting the result in a wanted order.






                              function plusMinus(arr) 
                              var freq = 1: 0, '-1': 0, 0: 0 ,
                              i, key;

                              for (i = 0; i < arr.length; i++)
                              freq[arr[i]]++;


                              for (key of [1, -1, 0])
                              console.log((freq[key] / arr.length).toFixed(6));



                              plusMinus([1, 1, 0, -1, -1]);








                              share|improve this answer


















                              • 1





                                The number can be any integer according the question. You might have to do: freq[Math.sign(arr[i])]++

                                – adiga
                                Mar 24 at 9:47












                              • @adiga, right, for any integer, the sign sould be sufficient.

                                – Nina Scholz
                                Mar 24 at 9:49











                              • @NinaScholz the order is right now but still deletes duplicates, the output should be 0.4,0.4,0.2 but its giving 0.4,0.2 , why is that?

                                – eng
                                Mar 24 at 10:32












                              • i don't understand the last output. what do you get?

                                – Nina Scholz
                                Mar 24 at 10:37











                              • @NinaScholz Sorry, it was my mistake. thats right

                                – eng
                                Mar 24 at 10:52














                              2












                              2








                              2







                              You could take an object with predifined properties, this prevents each loop for checking the existence and take an array of keys for getting the result in a wanted order.






                              function plusMinus(arr) 
                              var freq = 1: 0, '-1': 0, 0: 0 ,
                              i, key;

                              for (i = 0; i < arr.length; i++)
                              freq[arr[i]]++;


                              for (key of [1, -1, 0])
                              console.log((freq[key] / arr.length).toFixed(6));



                              plusMinus([1, 1, 0, -1, -1]);








                              share|improve this answer













                              You could take an object with predifined properties, this prevents each loop for checking the existence and take an array of keys for getting the result in a wanted order.






                              function plusMinus(arr) 
                              var freq = 1: 0, '-1': 0, 0: 0 ,
                              i, key;

                              for (i = 0; i < arr.length; i++)
                              freq[arr[i]]++;


                              for (key of [1, -1, 0])
                              console.log((freq[key] / arr.length).toFixed(6));



                              plusMinus([1, 1, 0, -1, -1]);








                              function plusMinus(arr) 
                              var freq = 1: 0, '-1': 0, 0: 0 ,
                              i, key;

                              for (i = 0; i < arr.length; i++)
                              freq[arr[i]]++;


                              for (key of [1, -1, 0])
                              console.log((freq[key] / arr.length).toFixed(6));



                              plusMinus([1, 1, 0, -1, -1]);





                              function plusMinus(arr) 
                              var freq = 1: 0, '-1': 0, 0: 0 ,
                              i, key;

                              for (i = 0; i < arr.length; i++)
                              freq[arr[i]]++;


                              for (key of [1, -1, 0])
                              console.log((freq[key] / arr.length).toFixed(6));



                              plusMinus([1, 1, 0, -1, -1]);






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Mar 24 at 9:04









                              Nina ScholzNina Scholz

                              207k16117190




                              207k16117190







                              • 1





                                The number can be any integer according the question. You might have to do: freq[Math.sign(arr[i])]++

                                – adiga
                                Mar 24 at 9:47












                              • @adiga, right, for any integer, the sign sould be sufficient.

                                – Nina Scholz
                                Mar 24 at 9:49











                              • @NinaScholz the order is right now but still deletes duplicates, the output should be 0.4,0.4,0.2 but its giving 0.4,0.2 , why is that?

                                – eng
                                Mar 24 at 10:32












                              • i don't understand the last output. what do you get?

                                – Nina Scholz
                                Mar 24 at 10:37











                              • @NinaScholz Sorry, it was my mistake. thats right

                                – eng
                                Mar 24 at 10:52













                              • 1





                                The number can be any integer according the question. You might have to do: freq[Math.sign(arr[i])]++

                                – adiga
                                Mar 24 at 9:47












                              • @adiga, right, for any integer, the sign sould be sufficient.

                                – Nina Scholz
                                Mar 24 at 9:49











                              • @NinaScholz the order is right now but still deletes duplicates, the output should be 0.4,0.4,0.2 but its giving 0.4,0.2 , why is that?

                                – eng
                                Mar 24 at 10:32












                              • i don't understand the last output. what do you get?

                                – Nina Scholz
                                Mar 24 at 10:37











                              • @NinaScholz Sorry, it was my mistake. thats right

                                – eng
                                Mar 24 at 10:52








                              1




                              1





                              The number can be any integer according the question. You might have to do: freq[Math.sign(arr[i])]++

                              – adiga
                              Mar 24 at 9:47






                              The number can be any integer according the question. You might have to do: freq[Math.sign(arr[i])]++

                              – adiga
                              Mar 24 at 9:47














                              @adiga, right, for any integer, the sign sould be sufficient.

                              – Nina Scholz
                              Mar 24 at 9:49





                              @adiga, right, for any integer, the sign sould be sufficient.

                              – Nina Scholz
                              Mar 24 at 9:49













                              @NinaScholz the order is right now but still deletes duplicates, the output should be 0.4,0.4,0.2 but its giving 0.4,0.2 , why is that?

                              – eng
                              Mar 24 at 10:32






                              @NinaScholz the order is right now but still deletes duplicates, the output should be 0.4,0.4,0.2 but its giving 0.4,0.2 , why is that?

                              – eng
                              Mar 24 at 10:32














                              i don't understand the last output. what do you get?

                              – Nina Scholz
                              Mar 24 at 10:37





                              i don't understand the last output. what do you get?

                              – Nina Scholz
                              Mar 24 at 10:37













                              @NinaScholz Sorry, it was my mistake. thats right

                              – eng
                              Mar 24 at 10:52






                              @NinaScholz Sorry, it was my mistake. thats right

                              – eng
                              Mar 24 at 10:52












                              0














                              You can use reduce.



                              Here idea is



                              • First loop through original array and check for the value.

                              • If value is zero we increment count of zero key.

                              • If value is positive we increment count of pos key.

                              • If value is negative we increment count of neg key.

                              • Finally we divide each count by length of array.




                              let arr = [1,1,0,-1,-1]

                              let op = arr.reduce((op,inp)=>
                              if(inp === 0)
                              op.zero.count++
                              else if (inp > 0)
                              op.pos.count++;
                              else
                              op.neg.count++;

                              return op
                              ,zero:count:0,pos:count:0,neg:count:0)


                              let final = Object.entries(op).map(([key,value])=>(
                              [key] : value.count / arr.length
                              ))

                              console.log(final)








                              share|improve this answer



























                                0














                                You can use reduce.



                                Here idea is



                                • First loop through original array and check for the value.

                                • If value is zero we increment count of zero key.

                                • If value is positive we increment count of pos key.

                                • If value is negative we increment count of neg key.

                                • Finally we divide each count by length of array.




                                let arr = [1,1,0,-1,-1]

                                let op = arr.reduce((op,inp)=>
                                if(inp === 0)
                                op.zero.count++
                                else if (inp > 0)
                                op.pos.count++;
                                else
                                op.neg.count++;

                                return op
                                ,zero:count:0,pos:count:0,neg:count:0)


                                let final = Object.entries(op).map(([key,value])=>(
                                [key] : value.count / arr.length
                                ))

                                console.log(final)








                                share|improve this answer

























                                  0












                                  0








                                  0







                                  You can use reduce.



                                  Here idea is



                                  • First loop through original array and check for the value.

                                  • If value is zero we increment count of zero key.

                                  • If value is positive we increment count of pos key.

                                  • If value is negative we increment count of neg key.

                                  • Finally we divide each count by length of array.




                                  let arr = [1,1,0,-1,-1]

                                  let op = arr.reduce((op,inp)=>
                                  if(inp === 0)
                                  op.zero.count++
                                  else if (inp > 0)
                                  op.pos.count++;
                                  else
                                  op.neg.count++;

                                  return op
                                  ,zero:count:0,pos:count:0,neg:count:0)


                                  let final = Object.entries(op).map(([key,value])=>(
                                  [key] : value.count / arr.length
                                  ))

                                  console.log(final)








                                  share|improve this answer













                                  You can use reduce.



                                  Here idea is



                                  • First loop through original array and check for the value.

                                  • If value is zero we increment count of zero key.

                                  • If value is positive we increment count of pos key.

                                  • If value is negative we increment count of neg key.

                                  • Finally we divide each count by length of array.




                                  let arr = [1,1,0,-1,-1]

                                  let op = arr.reduce((op,inp)=>
                                  if(inp === 0)
                                  op.zero.count++
                                  else if (inp > 0)
                                  op.pos.count++;
                                  else
                                  op.neg.count++;

                                  return op
                                  ,zero:count:0,pos:count:0,neg:count:0)


                                  let final = Object.entries(op).map(([key,value])=>(
                                  [key] : value.count / arr.length
                                  ))

                                  console.log(final)








                                  let arr = [1,1,0,-1,-1]

                                  let op = arr.reduce((op,inp)=>
                                  if(inp === 0)
                                  op.zero.count++
                                  else if (inp > 0)
                                  op.pos.count++;
                                  else
                                  op.neg.count++;

                                  return op
                                  ,zero:count:0,pos:count:0,neg:count:0)


                                  let final = Object.entries(op).map(([key,value])=>(
                                  [key] : value.count / arr.length
                                  ))

                                  console.log(final)





                                  let arr = [1,1,0,-1,-1]

                                  let op = arr.reduce((op,inp)=>
                                  if(inp === 0)
                                  op.zero.count++
                                  else if (inp > 0)
                                  op.pos.count++;
                                  else
                                  op.neg.count++;

                                  return op
                                  ,zero:count:0,pos:count:0,neg:count:0)


                                  let final = Object.entries(op).map(([key,value])=>(
                                  [key] : value.count / arr.length
                                  ))

                                  console.log(final)






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Mar 24 at 9:03









                                  Code ManiacCode Maniac

                                  14k21034




                                  14k21034





















                                      0














                                      Use reduce, map and filter:






                                      const arr = [1, 1, 0, -1, -1];

                                      const counts = arr.reduce((acc, curr) =>
                                      if (!curr) acc[0]++;
                                      else if (curr > 0) acc[1]++;
                                      else acc[2]++;
                                      return acc
                                      , [0, 0, 0]);

                                      const result = counts.map(e => e / arr.length).filter((e, i, a) => a.indexOf(e) == i);

                                      console.log(result);








                                      share|improve this answer



























                                        0














                                        Use reduce, map and filter:






                                        const arr = [1, 1, 0, -1, -1];

                                        const counts = arr.reduce((acc, curr) =>
                                        if (!curr) acc[0]++;
                                        else if (curr > 0) acc[1]++;
                                        else acc[2]++;
                                        return acc
                                        , [0, 0, 0]);

                                        const result = counts.map(e => e / arr.length).filter((e, i, a) => a.indexOf(e) == i);

                                        console.log(result);








                                        share|improve this answer

























                                          0












                                          0








                                          0







                                          Use reduce, map and filter:






                                          const arr = [1, 1, 0, -1, -1];

                                          const counts = arr.reduce((acc, curr) =>
                                          if (!curr) acc[0]++;
                                          else if (curr > 0) acc[1]++;
                                          else acc[2]++;
                                          return acc
                                          , [0, 0, 0]);

                                          const result = counts.map(e => e / arr.length).filter((e, i, a) => a.indexOf(e) == i);

                                          console.log(result);








                                          share|improve this answer













                                          Use reduce, map and filter:






                                          const arr = [1, 1, 0, -1, -1];

                                          const counts = arr.reduce((acc, curr) =>
                                          if (!curr) acc[0]++;
                                          else if (curr > 0) acc[1]++;
                                          else acc[2]++;
                                          return acc
                                          , [0, 0, 0]);

                                          const result = counts.map(e => e / arr.length).filter((e, i, a) => a.indexOf(e) == i);

                                          console.log(result);








                                          const arr = [1, 1, 0, -1, -1];

                                          const counts = arr.reduce((acc, curr) =>
                                          if (!curr) acc[0]++;
                                          else if (curr > 0) acc[1]++;
                                          else acc[2]++;
                                          return acc
                                          , [0, 0, 0]);

                                          const result = counts.map(e => e / arr.length).filter((e, i, a) => a.indexOf(e) == i);

                                          console.log(result);





                                          const arr = [1, 1, 0, -1, -1];

                                          const counts = arr.reduce((acc, curr) =>
                                          if (!curr) acc[0]++;
                                          else if (curr > 0) acc[1]++;
                                          else acc[2]++;
                                          return acc
                                          , [0, 0, 0]);

                                          const result = counts.map(e => e / arr.length).filter((e, i, a) => a.indexOf(e) == i);

                                          console.log(result);






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Mar 24 at 9:11









                                          Jack BashfordJack Bashford

                                          23k52251




                                          23k52251





















                                              0














                                              You can try using Array.reduce and the resulting array will have the fraction of positive number at the '0'th index, negative at '1'st and zero at the '2'nd index.



                                              Now if you want to control the count of the number of elements after decimal point, use Array.map at the end to transform it.






                                              const array = [1,1,0,-1,-1];
                                              function plusMinus(arr)
                                              const output = arr.reduce((acc, ele) =>
                                              if(ele > 0)
                                              if(ele < 0)
                                              acc[1] = ((acc[1]
                                              if(ele === 0) 0 ) + 1 / arr.length);

                                              return acc;
                                              , []).map(ele => ele.toFixed(6));
                                              console.log(...output);

                                              plusMinus(array);








                                              share|improve this answer





























                                                0














                                                You can try using Array.reduce and the resulting array will have the fraction of positive number at the '0'th index, negative at '1'st and zero at the '2'nd index.



                                                Now if you want to control the count of the number of elements after decimal point, use Array.map at the end to transform it.






                                                const array = [1,1,0,-1,-1];
                                                function plusMinus(arr)
                                                const output = arr.reduce((acc, ele) =>
                                                if(ele > 0)
                                                if(ele < 0)
                                                acc[1] = ((acc[1]
                                                if(ele === 0) 0 ) + 1 / arr.length);

                                                return acc;
                                                , []).map(ele => ele.toFixed(6));
                                                console.log(...output);

                                                plusMinus(array);








                                                share|improve this answer



























                                                  0












                                                  0








                                                  0







                                                  You can try using Array.reduce and the resulting array will have the fraction of positive number at the '0'th index, negative at '1'st and zero at the '2'nd index.



                                                  Now if you want to control the count of the number of elements after decimal point, use Array.map at the end to transform it.






                                                  const array = [1,1,0,-1,-1];
                                                  function plusMinus(arr)
                                                  const output = arr.reduce((acc, ele) =>
                                                  if(ele > 0)
                                                  if(ele < 0)
                                                  acc[1] = ((acc[1]
                                                  if(ele === 0) 0 ) + 1 / arr.length);

                                                  return acc;
                                                  , []).map(ele => ele.toFixed(6));
                                                  console.log(...output);

                                                  plusMinus(array);








                                                  share|improve this answer















                                                  You can try using Array.reduce and the resulting array will have the fraction of positive number at the '0'th index, negative at '1'st and zero at the '2'nd index.



                                                  Now if you want to control the count of the number of elements after decimal point, use Array.map at the end to transform it.






                                                  const array = [1,1,0,-1,-1];
                                                  function plusMinus(arr)
                                                  const output = arr.reduce((acc, ele) =>
                                                  if(ele > 0)
                                                  if(ele < 0)
                                                  acc[1] = ((acc[1]
                                                  if(ele === 0) 0 ) + 1 / arr.length);

                                                  return acc;
                                                  , []).map(ele => ele.toFixed(6));
                                                  console.log(...output);

                                                  plusMinus(array);








                                                  const array = [1,1,0,-1,-1];
                                                  function plusMinus(arr)
                                                  const output = arr.reduce((acc, ele) =>
                                                  if(ele > 0)
                                                  if(ele < 0)
                                                  acc[1] = ((acc[1]
                                                  if(ele === 0) 0 ) + 1 / arr.length);

                                                  return acc;
                                                  , []).map(ele => ele.toFixed(6));
                                                  console.log(...output);

                                                  plusMinus(array);





                                                  const array = [1,1,0,-1,-1];
                                                  function plusMinus(arr)
                                                  const output = arr.reduce((acc, ele) =>
                                                  if(ele > 0)
                                                  if(ele < 0)
                                                  acc[1] = ((acc[1]
                                                  if(ele === 0) 0 ) + 1 / arr.length);

                                                  return acc;
                                                  , []).map(ele => ele.toFixed(6));
                                                  console.log(...output);

                                                  plusMinus(array);






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Mar 24 at 9:20

























                                                  answered Mar 24 at 9:07









                                                  Amardeep BhowmickAmardeep Bhowmick

                                                  6,53621231




                                                  6,53621231





















                                                      0














                                                      Math.sign is your friend here.
                                                      Math.sign



                                                      Also lodash would really help this snippet to be cleaner, I highly recommend _.countBy. Lodash .countBy



                                                      Here's the code.






                                                      const plusMinus = (numbers) => 
                                                      // Count by Sign (-1, 0 1)
                                                      const countSign = _.countBy(numbers, Math.sign);
                                                      // _.countBy return object, of counted '1': 2, '0': 1, '-1': 2

                                                      // Print them in orders
                                                      const printOrder = [1, -1, 0];
                                                      printOrder.forEach(sign =>
                                                      console.log((countSign[sign] / numbers.length).toFixed(6));
                                                      );


                                                      const testArr = [1,1,0,-1,-1];
                                                      plusMinus(testArr);

                                                      <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>








                                                      share|improve this answer



























                                                        0














                                                        Math.sign is your friend here.
                                                        Math.sign



                                                        Also lodash would really help this snippet to be cleaner, I highly recommend _.countBy. Lodash .countBy



                                                        Here's the code.






                                                        const plusMinus = (numbers) => 
                                                        // Count by Sign (-1, 0 1)
                                                        const countSign = _.countBy(numbers, Math.sign);
                                                        // _.countBy return object, of counted '1': 2, '0': 1, '-1': 2

                                                        // Print them in orders
                                                        const printOrder = [1, -1, 0];
                                                        printOrder.forEach(sign =>
                                                        console.log((countSign[sign] / numbers.length).toFixed(6));
                                                        );


                                                        const testArr = [1,1,0,-1,-1];
                                                        plusMinus(testArr);

                                                        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>








                                                        share|improve this answer

























                                                          0












                                                          0








                                                          0







                                                          Math.sign is your friend here.
                                                          Math.sign



                                                          Also lodash would really help this snippet to be cleaner, I highly recommend _.countBy. Lodash .countBy



                                                          Here's the code.






                                                          const plusMinus = (numbers) => 
                                                          // Count by Sign (-1, 0 1)
                                                          const countSign = _.countBy(numbers, Math.sign);
                                                          // _.countBy return object, of counted '1': 2, '0': 1, '-1': 2

                                                          // Print them in orders
                                                          const printOrder = [1, -1, 0];
                                                          printOrder.forEach(sign =>
                                                          console.log((countSign[sign] / numbers.length).toFixed(6));
                                                          );


                                                          const testArr = [1,1,0,-1,-1];
                                                          plusMinus(testArr);

                                                          <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>








                                                          share|improve this answer













                                                          Math.sign is your friend here.
                                                          Math.sign



                                                          Also lodash would really help this snippet to be cleaner, I highly recommend _.countBy. Lodash .countBy



                                                          Here's the code.






                                                          const plusMinus = (numbers) => 
                                                          // Count by Sign (-1, 0 1)
                                                          const countSign = _.countBy(numbers, Math.sign);
                                                          // _.countBy return object, of counted '1': 2, '0': 1, '-1': 2

                                                          // Print them in orders
                                                          const printOrder = [1, -1, 0];
                                                          printOrder.forEach(sign =>
                                                          console.log((countSign[sign] / numbers.length).toFixed(6));
                                                          );


                                                          const testArr = [1,1,0,-1,-1];
                                                          plusMinus(testArr);

                                                          <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>








                                                          const plusMinus = (numbers) => 
                                                          // Count by Sign (-1, 0 1)
                                                          const countSign = _.countBy(numbers, Math.sign);
                                                          // _.countBy return object, of counted '1': 2, '0': 1, '-1': 2

                                                          // Print them in orders
                                                          const printOrder = [1, -1, 0];
                                                          printOrder.forEach(sign =>
                                                          console.log((countSign[sign] / numbers.length).toFixed(6));
                                                          );


                                                          const testArr = [1,1,0,-1,-1];
                                                          plusMinus(testArr);

                                                          <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>





                                                          const plusMinus = (numbers) => 
                                                          // Count by Sign (-1, 0 1)
                                                          const countSign = _.countBy(numbers, Math.sign);
                                                          // _.countBy return object, of counted '1': 2, '0': 1, '-1': 2

                                                          // Print them in orders
                                                          const printOrder = [1, -1, 0];
                                                          printOrder.forEach(sign =>
                                                          console.log((countSign[sign] / numbers.length).toFixed(6));
                                                          );


                                                          const testArr = [1,1,0,-1,-1];
                                                          plusMinus(testArr);

                                                          <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Mar 24 at 9:28









                                                          DoppioDoppio

                                                          942611




                                                          942611





















                                                              0














                                                              Here is another one-line solution using Array.reduce() and Array.forEach() functions:






                                                              const plusMinus = arr => arr
                                                              .reduce((res, curr) => ++res[!curr ? 2 : curr < 0 ? 1 : 0] && res, [0, 0, 0])
                                                              .forEach(i => console.log((i / arr.length).toFixed(6)));

                                                              plusMinus([1, 1, 0, -1, -1]);








                                                              share|improve this answer



























                                                                0














                                                                Here is another one-line solution using Array.reduce() and Array.forEach() functions:






                                                                const plusMinus = arr => arr
                                                                .reduce((res, curr) => ++res[!curr ? 2 : curr < 0 ? 1 : 0] && res, [0, 0, 0])
                                                                .forEach(i => console.log((i / arr.length).toFixed(6)));

                                                                plusMinus([1, 1, 0, -1, -1]);








                                                                share|improve this answer

























                                                                  0












                                                                  0








                                                                  0







                                                                  Here is another one-line solution using Array.reduce() and Array.forEach() functions:






                                                                  const plusMinus = arr => arr
                                                                  .reduce((res, curr) => ++res[!curr ? 2 : curr < 0 ? 1 : 0] && res, [0, 0, 0])
                                                                  .forEach(i => console.log((i / arr.length).toFixed(6)));

                                                                  plusMinus([1, 1, 0, -1, -1]);








                                                                  share|improve this answer













                                                                  Here is another one-line solution using Array.reduce() and Array.forEach() functions:






                                                                  const plusMinus = arr => arr
                                                                  .reduce((res, curr) => ++res[!curr ? 2 : curr < 0 ? 1 : 0] && res, [0, 0, 0])
                                                                  .forEach(i => console.log((i / arr.length).toFixed(6)));

                                                                  plusMinus([1, 1, 0, -1, -1]);








                                                                  const plusMinus = arr => arr
                                                                  .reduce((res, curr) => ++res[!curr ? 2 : curr < 0 ? 1 : 0] && res, [0, 0, 0])
                                                                  .forEach(i => console.log((i / arr.length).toFixed(6)));

                                                                  plusMinus([1, 1, 0, -1, -1]);





                                                                  const plusMinus = arr => arr
                                                                  .reduce((res, curr) => ++res[!curr ? 2 : curr < 0 ? 1 : 0] && res, [0, 0, 0])
                                                                  .forEach(i => console.log((i / arr.length).toFixed(6)));

                                                                  plusMinus([1, 1, 0, -1, -1]);






                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Mar 24 at 9:35









                                                                  AndriyAndriy

                                                                  8,84022135




                                                                  8,84022135



























                                                                      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%2f55322117%2flooping-through-javascript-object-without-sorting-based-on-keys%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

                                                                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                                                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript