Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!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: Tue, 27 Jan 2015 01:37:21 +0000 Organization: A noiseless patient Spider Lines: 40 Message-ID: <87twzdf1gu.fsf@bsb.me.uk> References: <26839541.MRbOrngyXZ@PointedEars.de> <87twzgl0aq.fsf@bsb.me.uk> <2697158.aGRKFDBAEn@PointedEars.de> <87lhkskr0r.fsf@bsb.me.uk> <4289032.9WYFBcEGMJ@PointedEars.de> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Injection-Info: mx02.eternal-september.org; posting-host="017616aa25f81ec581c44d76d61ba2f3"; logging-data="4774"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18cH7E9gYv/yy38paSc4RzRpa7BZHaTZM4=" Cancel-Lock: sha1:Ybd/1tcC4mclXBvfGpDgKx8Oh3A= sha1:pNOmvU+9p+56G3kKPM9Ya11IAjs= X-BSB-Auth: 1.f8ab44b9b240a43ca0c3.20150127013721GMT.87twzdf1gu.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:26725 Thomas 'PointedEars' Lahn writes: > Ben Bacarisse wrote: > >> Thomas 'PointedEars' Lahn writes: >>> Ben Bacarisse wrote: >>>> Thomas 'PointedEars' Lahn writes: >>>>> var counts = {}; >>>>> >>>>> for (var i = 0, len = a.length; i < len; ++i) >>>>> { >>>>> /* NOTE: hasOwnProperty() may be required */ >>>>> var e = a[i]; >>>>> e ? ++counts[e] : (counts[e] = 1); >>>>> } >>>> >>>> I think you meant counts[e] ? ++counts[e] : (counts[e] = 1); here (and >>>> immediately below): […] >>> >>> No, but >>> >>> if (e) { counts[e] ? ++counts[e] : (counts[e] = 1); } >> >> Why? > > Because there are sparse arrays ([To]String(“undefined”) === > "undefined"). Isn't if (a.hasOwnProperty(i)) { counts[e] ? ++counts[e] : (counts[e] = 1); } a better way to deal with sparse arrays in such a loop? Testing e seems rather heavy-handed, though it's not clear what the OP might want in anything but the simple case given. In a general counting loop one would probably want to count zeros and NaNs and so on. -- Ben.