Last active
March 6, 2018 09:29
-
-
Save vijaydeepak-tt/95637f5a0e9357a9fb41452e21b497af to your computer and use it in GitHub Desktop.
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
const array = [{age:44,name:'vinay'},{age:24,name:'deepak'},{age:74,name:'suresh'}]; | |
const sort = (type, array, direction) => { | |
return array.slice(0).sort(function(a,b) { | |
if(direction==='asc') { | |
return (a[type] > b[type]) ? 1 : (a[type] < b[type]) ? -1 : 0; | |
} | |
else if(direction==='dec') { | |
return (a[type] > b[type]) ? -1 : (a[type] < b[type]) ? 1 : 0; | |
} | |
}); | |
} | |
const ascAge = sort('age', array, 'asc') | |
const decAge = sort('age', array, 'dec') | |
const ascName = sort('name', array, 'asc') | |
const decName = sort('name', array, 'dec') | |
--------------------------------------------------------------------------------------------------------------------------------- | |
Array.prototype.sortBy = function(p) { | |
return this.slice(0).sort(function(a,b) { | |
return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0; | |
}); | |
} | |
objs = [{age:44,name:'vinay'},{age:24,name:'deepak'},{age:74,name:'suresh'}]; | |
objs.sortBy('age'); | |
// Returns | |
// [{"age":24,"name":"deepak"},{"age":44,"name":"vinay"},{"age":74,"name":"suresh"}] | |
objs.sortBy('name'); | |
// Returns | |
// [{"age":24,"name":"deepak"},{"age":74,"name":"suresh"},{"age":44,"name":"vinay"}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment