Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!news.swapon.de!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: function to get frequencies of a char array Date: Thu, 22 Jan 2015 23:09:36 +0000 Organization: A noiseless patient Spider Lines: 53 Message-ID: <877fwetntb.fsf@bsb.me.uk> References: Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="017616aa25f81ec581c44d76d61ba2f3"; logging-data="11140"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19g3MYDF+eHx4r86oUhGow+Xl4sRKtVcDA=" Cancel-Lock: sha1:9zYs5M5OFP+z7+E6pxKFJgppdS0= sha1:qhZA02fdA/N23XU4FCHKOhswbX0= X-BSB-Auth: 1.28c6856f1eb1976e74e4.20150122230936GMT.877fwetntb.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:26652 JRough writes: > the output should be: > a:1,b:1,j:4,c:1,d:1 The code does no output. You mean these should be the value in the map, yes? > I am trying to use a map and use the keys as the char and the values > as the count but I'm getting undefined. thanks, This looks like coursework, so my intuition is just to ask some questions that I hope will lead you to an answer. > function frequencies(){ > var arr = ['a', 'b', 'j','c', 'd', 'j', 'j', 'j']; > var key, value; > for(i=0; i< arr.length; i++){ You should declare i as well. You can do it in the for statement. > var myMap = new Map(); > if (arr[i]==arr[i+1]){ This will access beyond the end of the array and I can't see what it has to do with counting. You want to set the map entry to 1 when you see a letter for the first time, not when you see a letter that is different to the one that follows it. The key thing here is that you get the value out of the map. That is what tells you if you have seen this letter before. > myMap.set(key=i, value= value+1) value has not been set. value = value + 1 sets value to one mode than undefined. Not what you mean at all. > }else{ > myMap.set(key=i,"1") Why "1" rather than 1? Why key=i rather than i? Is i even the right key? > }; > }; The function returns nothing, so it has no point. > } > frequencies(); -- Ben.