Below is the solution I would use. This solution provides a keys only sort, a values only sort, a keys then values sort, and a values then keys sort.
class FunkySort {
sort (sortType) {
switch (sortType) {
case 'keysOnly':
return data => this._sortByKey(data);
case 'valuesOnly':
return data => this._sortByValue(data);
case 'valuesPrimary':
return data => {
data = this._sortByKey(data);
return this._sortByValue(data);
};
case 'keysPrimary':
return data => {
data = this._sortByValue(data);
return this._sortByKey(data);
};
}
}
_sortByKey (data) {
return data.sort((a, b) => {
var keyA = Object.keys(a)[0];
var keyB = Object.keys(b)[0];
return keyA < keyB ? -1 : keyA > keyB ? 1 : 0;
});
}
_sortByValue (data) {
return data.sort((a, b) => {
// note that in Node >=v7 you could use `Object.values()`, but not in <v7.0
var valueA = a[Object.keys(a)[0]];
var valueB = b[Object.keys(b)[0]];
return valueA < valueB ? -1 : valueA > valueB ? 1 : 0;
});
}
}
const dataArr = [{name:'John'},{age:25},{address:'some street'}];
const fs = new FunkySort();
fs.sort('keysPrimary')(dataArr);
Note that fs.sort
is a curried function. The first call sets the type of sort to be done, so fs.sort('keysPrimary')
returns a function that takes an array of objects and sorts it first by the values, and then by the keys, resulting in an array of objects sorted by key, and if there are multiple objects with the same key, those are sorted by value.
If you don't need this level of flexibility in the type of sort, then just the _sortByKey
helper method should suffice.