banner



How To Find Mode In Javascript

#i

  • New D.I.C Caput

Reputation: 2

  • View blog
  • Posts: 21
  • Joined: 31-March 15

Javascript Beginner: Discover the Mode in an Array

Posted 01 June 2022 - 03:49 PM

Here I want to discover the mode of an array, if two numbers announced the same amount of times, I just output the first one. It'due south a uncomplicated concept and I am 85% at that place. I but need assistance with 1 matter. I am only getting comfortable with nested loops and this count's properly just it but gives me a return of the last number that repeated, not the one that repeated the nigh times.

I know what I want to do, I'm only stuck on how to write it out. I demand information technology to add to the counter each time it finds a like number, only when it comes to a new number I demand it to agree that counter value unless the next counter value is higher, and so supervene upon the mode variable.

I have been staring at it for virtually 30 minutes now and I'm suck. I hope someone tin can explain this easily to a beginner! Thanks in accelerate.

function SimpleMode(arr) {  var way = 0; var count = 0;   for(var i = 0; i < arr.length; i++){     for(var j = 0; j < i; j++){        if(arr[j] === arr[i]){            mode = arr[j];            count++;            panel.log(count);        }     }   }   return mode; }    SimpleMode([eight,seven,8,8,9,three,3]);            


Is This A Good Question/Topic? 0

  • +

#2 ArtificialSoldier User is offline

Reputation: 3135

  • View blog
  • Posts: 8,936
  • Joined: fifteen-January 14

Re: Javascript Beginner: Find the Fashion in an Array

Posted 01 June 2022 - 04:19 PM

One mode to exercise it is to create a separate array where the keys are the values that you discover, and the values are the counts. Once you build that array then you can go through and observe the maximum value, and the corresponding key will be the mode.

#three /n.colavita User is offline

  • New D.I.C Head

Reputation: 2

  • View blog
  • Posts: 21
  • Joined: 31-March 15

Re: Javascript Beginner: Notice the Manner in an Assortment

Posted 01 June 2022 - 04:27 PM

Ahhh ok that makes sense. Thank you. I volition endeavour that approach.

#iv /n.colavita User is offline

  • New D.I.C Head

Reputation: 2

  • View blog
  • Posts: 21
  • Joined: 31-March fifteen

Re: Javascript Beginner: Find the Mode in an Assortment

Posted 02 June 2022 - 03:23 PM

After some time, reading over your solution ArtificialSoldier, do you lot mean create a nested array, and each array has a number (from the original array) and a count for how many times it shows upwards? Then go through that new assortment and find the highest count?

and so it would look like this? (first number is the number in the original array, second is the count)

function simpleMode(num)  var newArr = [[2,1],[3,1],[four,3],[5,two],[half-dozen,1]]   return simpleMode([2,iii,4,4,4,five,5,6])            

#five ArtificialSoldier User is offline

Reputation: 3135

  • View blog
  • Posts: 8,936
  • Joined: 15-Jan 14

Re: Javascript Beginner: Discover the Manner in an Array

Posted 03 June 2022 - 12:20 PM

I guess that'southward one option. I was suggesting something where the key or index is the number, and the value is the count. Then for the assortment above, the consequence would be:

newArr[2] = 1; newArr[3] = 1; newArr[4] = 3; newArr[v] = ii; newArr[vi] = 1;            

Using a structure like that would exist faster than having to loop through the array to observe the number you're looking for.

#six felgall User is offline

  • D.I.C Regular

Reputation: 68

  • View blog
  • Posts: 365
  • Joined: 22-Feb 14

Re: Javascript Beginner: Find the Mode in an Array

Posted 03 June 2022 - 12:27 PM

View Post/n.colavita, on 02 June 2022 - 08:49 AM, said:

function SimpleMode(arr) {  var way = 0; var count = 0;   for(var i = 0; i < arr.length; i++){     for(var j = 0; j < i; j++){        if(arr[j] === arr[i]){            mode = arr[j];            count++;            panel.log(count);        }     }   }   return mode; }    SimpleMode([8,7,8,8,9,3,3]);              

The following volition extract the manner of whatsoever assortment by converting the array to a string and using a regular expression to work out which element occurs the nearly times. Information technology returns an array since there can exist more 1 way.

function AnyMode(arr) {  max = 0; way = []; str = arr.sort(); str = "~" + str.join('~~') + "~" str.supercede( /(~-*\d+~)\1*/m, role(a, b ) {     var m = a.length / b.length;     if (max <= 1000 ) {         if (max < m) {way = [];max = chiliad;}         fashion.push( b.supplant(/~/g,""));     }  }); return fashion; }            

This post has been edited past felgall: 03 June 2022 - 12:32 PM

#7 modi123_1 User is offline

Reputation: 16480

  • View blog
  • Posts: 65,328
  • Joined: 12-June 08

Re: Javascript Beginner: Detect the Mode in an Assortment

Posted 04 June 2022 - 07:25 AM

@felgall - Information technology tends to short excursion the educational value of the homework when you dump out a completed, and undocumented/unexplained, solution. Let'due south avoid that in the future, and look at the bigger picture of the homework'southward goals (teaching assortment navigation/manipulation, loops, etc).

#viii /northward.colavita User is offline

  • New D.I.C Head

Reputation: 2

  • View blog
  • Posts: 21
  • Joined: 31-March 15

Re: Javascript Beginner: Discover the Mode in an Assortment

Posted 04 June 2022 - 07:36 AM

Exactly my thoughts. Fifty-fifty though that code is besides advanced to me at the moment anyway and I tin't make sense of information technology, I don't want just answers. I want to larn concepts and why certain code does what.

View Postmodi123_1, on 04 June 2022 - 07:25 AM, said:

@felgall - It tends to short circuit the educational value of the homework when you dump out a completed, and undocumented/unexplained, solution. Allow'due south avoid that in the time to come, and look at the bigger picture of the homework's goals (teaching array navigation/manipulation, loops, etc).


#9 felgall User is offline

  • D.I.C Regular

Reputation: 68

  • View blog
  • Posts: 365
  • Joined: 22-February 14

Re: Javascript Beginner: Find the Mode in an Array

Posted 04 June 2022 - 12:14 PM

View Postmodi123_1, on 05 June 2022 - 12:25 AM, said:

@felgall - It tends to brusque circuit the educational value of the homework when you dump out a completed, and undocumented/unexplained, solution.

No it doesn't - to be able to use the answer the student needs to understand information technology in order to be able to explicate to the teacher how it works. So with insufficient understanding of how it works the student can't utilize it every bit their reply to the homework. They can however see how a good solution to the particular trouble can be coded that takes advantage of more than advanced aspects of Javascript than they currently know.

My answer simply has no value if the sole goal is to laissez passer the class. If the goal is to acquire Javascript then the respond is useful equally y'all already know what it does and simply don't know how it does it. That provides an opportunity to learn more than Javascript. There are a series of statements at that place that you can acquire about and so every bit to learn how the presented lawmaking solves the problem. Plus you tin can e'er inquire what individual statements practise. Then it doesn't short circuit the didactics process - information technology provides more opportunity to acquire.

It is only when someone posts an respond that is just what the teacher would be expecting the pupil to provide that it short circuits the education process as then the student doesn't fifty-fifty learn the lawmaking the teacher is expecting them to learn.

#10 modi123_1 User is offline

Reputation: 16480

  • View blog
  • Posts: 65,328
  • Joined: 12-June 08

Re: Javascript Beginner: Observe the Mode in an Assortment

Posted 04 June 2022 - 12:18 PM

.. so the complete jibberish helps no one but those who know what it ways? It seems similar a big educational gap that can exist filled by taking an extra few minutes to document the code being used and what it is doing.

Let'southward be a little more inclusive and positive with the solutions!

#11 felgall User is offline

  • D.I.C Regular

Reputation: 68

  • View blog
  • Posts: 365
  • Joined: 22-February 14

Re: Javascript Beginner: Find the Mode in an Array

Posted 04 June 2022 - 01:37 PM

View Postmodi123_1, on 05 June 2022 - 05:18 AM, said:

.. and so the consummate jibberish

Information technology is only jibberish to those who don't want to learn Javascript and merely expect to be spoonfed. At best they may eventually exist able to consider themselves Javascript beginners.

There are and then many resources available that anyone who wants to learn what any item piece of Javascript code does tin can easily do and then. In that location is even a viscid mail service at the elevation of the thread that lists a lot of them including reference books and online references.

Alternatively you can notice out what lawmaking does by running information technology. Sites such equally jsfiddle and jsbin allow you to mail service Javascript into their page and run it. By placing console.log statements at diverse points you tin can easily piece of work out what the individual statements do.

There are as well sites where you tin mail service Javascript code and accept it reformatted to make information technology more readable.

There is a link in my signature to a site with hundreds of examples of Javascript code with explanations of what all the individual commands practise. All but one of the commands that are in the code I posted are explained in item at that place (thankyou for helping me discover a command that is missing from the site - I'll add together an explanation for that one in the next few days).

Most Javascript courses that are a role of a larger course were created a long time agone and Javascript has changed significantly since and so so if you take one of those courses and so you need to unlearn virtually half of the grade material and acquire how to write information technology properly for modern browsers before y'all will be able to progress beyond beginner. Anyway, beyond the very nuts Javascript is not something that can be taught, information technology is something that must be learnt by examining code and working out for yourself how information technology works and so trying to ameliorate on it.

#12 modi123_1 User is offline

Reputation: 16480

  • View blog
  • Posts: 65,328
  • Joined: 12-June 08

Re: Javascript Beginner: Observe the Mode in an Assortment

Posted 04 June 2022 - 01:46 PM

Fair enough, but in the future please endeavor to add together comments/documentation/context to your code drops. Remember this is a site with a variety of folk at a wide range of skill levels. Wouldn't it be better to have some awesome piece of code understood past near, and help everyone beyond the levels? I would detest to meet your hard work dismissed or bypassed considering you did not accept a few extra minutes on the documentation/comments/context to brand it attainable for folk.

#xiii /north.colavita User is offline

  • New D.I.C Head

Reputation: 2

  • View blog
  • Posts: 21
  • Joined: 31-March 15

Re: Javascript Beginner: Find the Manner in an Assortment

Posted 04 June 2022 - 02:07 PM

Posted Image

#fourteen felgall User is offline

  • D.I.C Regular

Reputation: 68

  • View blog
  • Posts: 365
  • Joined: 22-February xiv

Re: Javascript Beginner: Find the Mode in an Array

Posted 05 June 2022 - 01:48 PM

View Postmodi123_1, on 05 June 2022 - 06:46 AM, said:

Off-white enough, merely in the hereafter please try to add comments/documentation/context to your code drops.

I have about twenty web pages worth of description on how that lawmaking works - way too much to mail here.

To get people started on how the code works, hither is a copy with some console.log() statements added so you tin can see the results at diverse points in the process (with a numbered comment subsequently each so you can tell which of the results relate to which in the below commentary).

function AnyMode(arr) { max = 0; mode = []; str = arr.sort(); str = "~" + str.join('~~') + "~"; panel.log(str); // one   str.replace( /(~\-?\d+~)\ane*/yard, function(a, b ) {     panel.log(a + ',' + b ); // 2     var grand = a.length / b.length;     if (max <= yard ) {         if (max < m) {mode = [];max = m;}         mode.push button( +b.replace(/~/m,""));     } }); return manner; }  panel.log(AnyMode([8,7,15,3,-half dozen,eight,8,27,9,-27,three,3])); // iii            

The console log statement at // i will brandish the following string:

"~-27~~-vi~~xv~~27~~3~~3~~3~~vii~~8~~eight~~8~~9~"

Note that the numbers have been sorted then all occurrences of the same number are together. They are not in numerical order because nosotros didn't provide a function to the sort to override the normal sort society. We don't care what order they are in every bit long as all copies of the aforementioned number are together.

The panel log statement at // 2 runs eight times (equally that is how many different unique values there are in the array). It displays each of the following in plow:

"~-27~,~-27~"
"~-6~,~-half-dozen~"
"~15~,~15~"
"~27~,~27~"
"~3~~3~~iii~,~3~"
"~vii~,~vii~"
"~8~~8~~8~,~eight~"
"~9~,~9~"

The 'a' parameter values are the what the /(~\-?\d+~)\1*/m regular expression pulls out of the string while the 'b' parameter values are the content of the () portion of the expression.

The // three console log argument displays the result of the AnyMode() call - those numbers that occur the most times in the array:

[3, 8]

The // one and // 2 panel log calls basically shows the before and after values for the /(~\-?\d+~)\1*/1000, part(a, b) {...} argument (the almost complex argument in the code). Yous could of course add more console.log() calls to meet what the other individual statements practise if you don't sympathize them. If you get to http://jsbin.com/ you can employ the Javascript tab to post the Javascript without needing whatsoever HTML and and then view the results in the console tab.

This post has been edited by felgall: 05 June 2022 - 01:50 PM

#xv Martyr2 User is offline

Reputation: 5615

  • View blog
  • Posts: xiv,693
  • Joined: 18-April 07

Re: Javascript Beginner: Find the Mode in an Array

Posted 05 June 2022 - 02:09 PM

But a piddling note to mention hither for the original poster, do remember that a set up can have no manner or multiple modes. In this example you may want to render a value that would non exist confused with one of the elements in the set if there is no manner and a way to return multiple modes if it has one. ArtificialSoldier said information technology best with finding a count first, then from that count list determining if it has a mode, if there is actually more than one mode or has no mode at all.

:)

Source: https://www.dreamincode.net/forums/topic/376769-javascript-beginner-find-the-mode-in-an-array/

Posted by: adcoxhistiamseent.blogspot.com

0 Response to "How To Find Mode In Javascript"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel