Skip to content

Instantly share code, notes, and snippets.

@Shwartz
Last active June 20, 2018 10:16
Show Gist options
  • Save Shwartz/93e78550af29e8b393fe246b65b0e67f to your computer and use it in GitHub Desktop.
Save Shwartz/93e78550af29e8b393fe246b65b0e67f to your computer and use it in GitHub Desktop.
ES6 style sorting helpers for objects
const asc = (left, right) => left < right ? -1 : left > right ? 1 : 0;
const desc = (left, right) => left > right ? -1 : left < right ? 1 : 0;
const sort = (array, column, order) => array.sort(({[column]: left}, {[column]: right}) => order(left, right));
export const sortAsc = (array, column) => sort(array, column, asc);
export const sortDesc = (array, column) => sort(array, column, desc);
@Shwartz
Copy link
Author

Shwartz commented Jun 20, 2018

Usage

Let's say you want to sort out this obj by column B:

const arr = [
  {a: 'a1', b: 'b1', c: 'c1'},
  {a: 'a2', b: 'b2', c: 'c2'},
  {a: 'a3', b: 'b3', c: 'c3'},
]

get new array sorted by column B Descending

const arrSortedByB = sortDesc(arr, 'b');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment