Path: csiph.com!weretis.net!feeder4.news.weretis.net!feeder1.news.weretis.net!news.solani.org!.POSTED!not-for-mail From: Thomas 'PointedEars' Lahn Newsgroups: comp.lang.javascript Subject: Re: Bubblesort Date: Tue, 08 Mar 2016 23:35:10 +0100 Organization: PointedEars Software (PES) Lines: 52 Message-ID: <2815605.oGPRxZOVvt@PointedEars.de> References: <0d68ee6d-8a80-439e-ae04-17743584e2e4@googlegroups.com> <086a7397-459b-46e3-b83c-cfc7edf4188a@googlegroups.com> <7b1ee9db-4732-48e1-be7e-37ba62db4c6e@googlegroups.com> Reply-To: Thomas 'PointedEars' Lahn Mime-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 8Bit X-Trace: solani.org 1457476510 15573 eJwFwYEBwCAIA7CXtLRlO4eh/H/CEoW3O2mZGs2Xjc2OPe/B9CJgwgVcxZzSc7Qcq8iE8v4RcxBg (8 Mar 2016 22:35:10 GMT) X-Complaints-To: abuse@news.solani.org NNTP-Posting-Date: Tue, 8 Mar 2016 22:35:10 +0000 (UTC) User-Agent: KNode/4.14.2 X-User-ID: eJwVy8kBwCAIBMCW0AWEcpCj/xJM5j8CXZqHVZRlZDro4qi43xubN0VBMxI8ZTW2q9syQQvqXdGcDqu/fKfoAW5VFf0= Cancel-Lock: sha1:Rb/4ax+lv0KjBaueLlQdEq6XrmY= X-NNTP-Posting-Host: eJwFwYEBwDAEBMCVyMfTcRD2H6F3BirbL43X1haHL8Unei2S8ikqz+OUN9ILiPGhQiqgsz8d8BEs Xref: csiph.com comp.lang.javascript:29861 Stefan Weiss wrote: > On 03/04/2016 14:41, jonas.thornvall@gmail.com wrote: >>> I thought this would sort the property "subarray" nodelinks. >>> >>> arr[0].nodelinks.sort(); >>> >>> But after sort it write out same content as before sort. >>> 1,10,11,12,13,14,15,16,17,2,3,4,5,6,7,8,9 >>> […] > > The result you describe is typically what you get when you use sort() > with string elements instead of numbers. Ideally, you should make sure > that you actually insert numbers into `arr[x].nodelinks`, not strings. As Ben pointed out in , that would not help. But see also my follow-up to his posting. > Alternatively, you can sort string array elements using a numeric > comparison function: > > arr[x].nodelinks.sort((a, b) => a - b); > > Or in a more verbose form (but with better UA compatibility): > > function compareNumeric (a, b) > { > return a - b; > } > > arr[x].nodelinks.sort(compareNumeric); For reasonable backwards-compatibility, the function declaration is unnecessary/unwise, unless the comparator is declared locally *and* used locally more than once (in which case a function declaration/variable initialization saves memory). Function expressions are backwards-compatible down to JavaScript 1.3 and JScript 5.0 at least (Netscape Navigator 4.06+, Internet Explorer 5.0), therefore marked “safe” in the ECMAScript Support Matrix since its inception in 2005 (IIRC). arr[x].nodelinks.sort(function (a, b) { return a - b; }); This is also the equivalent syntax for the ECMAScript 2015 arrow function syntax as used above. -- PointedEars FAQ: | SVN: Twitter: @PointedEars2 | ES Matrix: Please do not cc me. / Bitte keine Kopien per E-Mail.