Created
November 18, 2023 14:28
-
-
Save marcelomf/69323276836f9921179fa233a79541ba to your computer and use it in GitHub Desktop.
Add sortBy in Array object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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