var s = "Sorting Shuffling Randoming Array";
var dogs = [];
//the module
var Dog = function(id){
this.id = id;
this.name = "Dog"+id;
this.dimensions = {x:rand(0,5),y:rand(0,5)};
}
//create the array
for(var i=0; i<10; i++){
dogs.push(new Dog(i));
}
//shuffle
shuffle(dogs);
//basic sort - sort by one property on root of obj
//dogs.sort(basicSortCompare);
//adv sort - sort by a nested property within a nested obj
//dogs.sort(dynamicNestedSort("dimensions","y"));
//adv sort - sort reverse on nested property
dogs.sort(dynamicNestedSort("dimensions","-y"));
console.log(dogs);
function rand(min,max){
return Math.floor((Math.random() * max) + min);
}
//basic sort, no nested property
function basicSortCompare(a,b){
if (a.id < b.id)
return -1;
if (a.id > b.id)
return 1;
return 0;
}
//shuffle array
function shuffle (array) {
var i = 0, j = 0, temp = null
for (i = array.length - 1; i > 0; i -= 1) {
j = Math.floor(Math.random() * (i + 1))
temp = array[i]
array[i] = array[j]
array[j] = temp
}
}
//best sorting method that handles both sorting down to 1 level deep
//use "-1" prepended to variable name to do reverse sorting
function dynamicNestedSort(property, nestedProperty){
var sortOrder = 1;
var canSort = property != null ? true : false; //need at least property to not be null
//detect if param1 is negative
if(canSort && property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
//detect if param2 is negative
if(nestedProperty != null && nestedProperty[0] === "-"){
sortOrder = -1;
nestedProperty = nestedProperty.substr(1);
}
if(canSort && nestedProperty == null){
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}else if(canSort){
return function (a,b) {
try{
var result =...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.