Let's say I have the array
I want to randomize this through the sort function and not through a separate shuffle method.Code:var a = [1, 2, 3, 4, 5, 6];
If I'm not mistaken, the following is not a fair comparatorCode:a.sort(function(a, b) { // do something });
Or at least I'm almost certain this is not truely random.Code:a.sort(function() { return Math.random(); });
If anything, the comparator needs to model this form for my page because I want to use something likeCode:a.sort(function(a, b) { a = Math.random(); b = Math.random(); if(a > b) return 1; if(a < b) return -1 return 0; });
Any ideas?Code:function sortList(f) { Array.prototype.filter.call(document.getElementsByTagName("li"), (function() { var regex = /^\d+$/; return function(el) { return el.value && regex.test(el.value); }; })()).sort(function(a, b) { var x = a; a = f(a); b = f(b); while(true) { try { if(a > b) return 1; if(a < b) return -1; return 0; } catch(e) { a = f(x); // IE bug } } }).forEach((function() { var i = 1; return function(el) { el.parentNode.appendChild(el); el.value = (i++).toString(); }; })()); } sortList(function(el) { el.firstChild.nodeValue; }); sortList(function(el) { Math.random(); // wierd results! });



Reply With Quote



Bookmarks