Skip to content

Instantly share code, notes, and snippets.

@nhatnx
Created December 12, 2018 03:46
Show Gist options
  • Select an option

  • Save nhatnx/404d4f3c442b3c7c54243164857ed9e9 to your computer and use it in GitHub Desktop.

Select an option

Save nhatnx/404d4f3c442b3c7c54243164857ed9e9 to your computer and use it in GitHub Desktop.
Sort object by value of a key AND by key
// by_value_of_key
// e.g. array = [{index: 3, sortProp: 'aaa'}, {index: 1, sortProp: 'ccc'}, {index: 2, sortProp: 'bbb'}]
var sortProp = "keyToSortByItsValues"
array.sort(function (left, right) {
let a = left[sortProp];
let b = right[sortProp];
if (a !== b) {
if (a > b || a === void 0) return -1;
if (a < b || b === void 0) return 1;
}
return left.index - right.index; // arrayItem.index is a key contains index value
});
// by_key
// helper functions to sort by key
let toPairs = s => Object.keys(s).map(k => [k, s[k]]);
let fromPairs = a => a.reduce((s, [k, v]) => Object.assign(s, {[k]: v}), {});
let cmp = (a, b) => (a > b) - (a < b);
// sorting
maindata = fromPairs(
toPairs(maindata).sort(
(x, y) => cmp(y[1], x[1]) || cmp(y[0], x[0])
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment