I was working with javascript sort method to sort out an array of objects with a scenario like I needed to sort by object property 'name' but using only sort method didn't fullfill my requirements so I came with additional method implemented as a middleware of sort method like below:
Current Result:
const objArray = [
{ name: 'Z', age: 32},
{ name: 'B', age: 23},
{ name: 'C', age: 45},
{ name: 'E', age: 33},
{ name: 'A', age: 53}
];
Expected result:
const objArray = [
{ name: 'A', age: 53}
{ name: 'B', age: 23},
{ name: 'C', age: 45},
{ name: 'E', age: 33},
{ name: 'Z', age: 32}
];
objArray.sort(sortBy('name', false));
function sortBy(key, reverse) {
var moveSmaller = reverse ? 1 : -1;
var moveLarger = reverse ? -1 : 1;
return function(a, b) {
if (a[key] < b[key]) {
return moveSmaller;
}
if (a[key] > b[key]) {
return moveLarger;
}
return 0;
};
}
It may help someone like me :)
Current Result:
const objArray = [
{ name: 'Z', age: 32},
{ name: 'B', age: 23},
{ name: 'C', age: 45},
{ name: 'E', age: 33},
{ name: 'A', age: 53}
];
Expected result:
const objArray = [
{ name: 'A', age: 53}
{ name: 'B', age: 23},
{ name: 'C', age: 45},
{ name: 'E', age: 33},
{ name: 'Z', age: 32}
];
objArray.sort(sortBy('name', false));
function sortBy(key, reverse) {
var moveSmaller = reverse ? 1 : -1;
var moveLarger = reverse ? -1 : 1;
return function(a, b) {
if (a[key] < b[key]) {
return moveSmaller;
}
if (a[key] > b[key]) {
return moveLarger;
}
return 0;
};
}
It may help someone like me :)
No comments:
Post a Comment