Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!weretis.net!feeder1.news.weretis.net!news.solani.org!.POSTED!not-for-mail From: Thomas 'PointedEars' Lahn Newsgroups: comp.lang.javascript Subject: Re: function to get frequencies of a char array Date: Tue, 27 Jan 2015 01:00:16 +0100 Organization: PointedEars Software (PES) Lines: 40 Message-ID: <4289032.9WYFBcEGMJ@PointedEars.de> References: <26839541.MRbOrngyXZ@PointedEars.de> <87twzgl0aq.fsf@bsb.me.uk> <2697158.aGRKFDBAEn@PointedEars.de> <87lhkskr0r.fsf@bsb.me.uk> Reply-To: Thomas 'PointedEars' Lahn Mime-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 8Bit X-Trace: solani.org 1422316854 3532 eJwFwYERAEEEBLCW3rGLcjD0X8InUArHjaDhcHzZnoodfSeHoV1HCVnTLTuxwr2o/izd4wciGxFy (27 Jan 2015 00:00:54 GMT) X-Complaints-To: abuse@news.solani.org NNTP-Posting-Date: Tue, 27 Jan 2015 00:00:54 +0000 (UTC) User-Agent: KNode/4.14.2 X-User-ID: eJwFwQkBwDAIA0BLrJBA5VAe/xJ2B+XHciNoWKyJHG4UrZseQa2PnXuR6LQauFWHv9vSOW5P5ZTOPjuYvT9SehYB Cancel-Lock: sha1:Cioyeas3GdQHX5icuUYPL17MbG0= X-NNTP-Posting-Host: eJwFwQcBADAIAzBLnFKYnB3wL2FJOJU3wSBiYg4XjpIV20Og0lzPFVO4as/cWjBau8yyMz/9aw/g Xref: csiph.com comp.lang.javascript:26720 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"). Your variant suffices for sparse arrays iterated over with the “for–in” statement, provided that there are no other inherited or own enumerable properties (otherwise .hasOwnProperty() needs to be used and the property name needs to be checked against the specification for Array indexes). > And did you mean to add the if (e) test to the forEach examples, too? No, Array.prototype.forEach() already tests internally if the numeric property name is an index. That is also the reason why it is so very inefficient with sufficiently sparse large arrays. -- PointedEars FAQ: | SVN: Twitter: @PointedEars2 | ES Matrix: Please do not cc me. / Bitte keine Kopien per E-Mail.