Skip to content

Instantly share code, notes, and snippets.

@marcelomf
Created November 18, 2023 14:28
Show Gist options
  • Save marcelomf/69323276836f9921179fa233a79541ba to your computer and use it in GitHub Desktop.
Save marcelomf/69323276836f9921179fa233a79541ba to your computer and use it in GitHub Desktop.
Add sortBy in Array object
(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 (let i=this.length;i;){
let o = this[--i];
this[i] = [].concat(f.call(o,o,i),o);
}
this.sort(function(a,b){
for (let i=0,len=a.length;i<len;++i){
if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
}
return 0;
});
for (let 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