Skip to content

Instantly share code, notes, and snippets.

@yagopv
Created January 22, 2014 11:12
Show Gist options
  • Save yagopv/8557026 to your computer and use it in GitHub Desktop.
Save yagopv/8557026 to your computer and use it in GitHub Desktop.
Order array Javascript
// Simple
array.sort(function(a,b){
a = new Date(a.date);
b = new Date(b.date);
return a<b?-1:a>b?1:0;
});
// Generic
(function(){
if (typeof Object.defineProperty === 'function'){
try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
}
if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;
function sb(f){
for (var i=this.length;i;){
var o = this[--i];
this[i] = [].concat(f.call(o,o,i),o);
}
this.sort(function(a,b){
for (var i=0,len=a.length;i<len;++i){
if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
}
return 0;
});
for (var i=this.length;i;){
this[--i]=this[i][this[i].length-1];
}
return this;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment