Skip to content

Instantly share code, notes, and snippets.

@orther
Created January 27, 2017 17:34
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save orther/0081dda0006fb2e23fdd41b7a8c648e0 to your computer and use it in GitHub Desktop.
Save orther/0081dda0006fb2e23fdd41b7a8c648e0 to your computer and use it in GitHub Desktop.
A few simple examples of sorting with Ramda's sortBy function.
import R from 'ramda';
const items = [
{id: 1, name: 'Al', country: 'AA'},
{id: 2, name: 'Connie', country: 'BB'},
{id: 3, name: 'Doug', country: 'CC'},
{id: 4, name: 'Zen', country: 'BB'},
{id: 5, name: 'DatGGboi', country: 'AA'},
{id: 6, name: 'Connie', country: 'AA'},
];
const propName = R.prop('name');
const propCountry = R.prop('country');
// ~ ORDER BY name ASC, country ASC
const sortOne = R.sortWith([
R.ascend(propName),
R.ascend(propCountry),
]);
// ~ ORDER BY country ASC, name ASC
const sortTwo = R.sortWith([
R.ascend(propCountry),
R.ascend(propName),
]);
// ~ ORDER BY LENGTH(state) DESC, country ASC
const sortThree = R.sortWith([
R.descend(R.compose(R.length, propName)),
R.ascend(propCountry),
]);
console.group('sortOne ~ ORDER BY name ASC, country ASC');
console.table(sortOne(items));
console.groupEnd();
console.log();
console.group('sortTwo ~ ORDER BY country ASC, name ASC');
console.table(sortTwo(items));
console.groupEnd();
console.log();
console.group('sortThree ~ ORDER BY LENGTH(state) DESC, country ASC');
console.table(sortThree(items));
console.groupEnd();
console.log();
@orther
Copy link
Author

orther commented Jan 27, 2017

sortOne ~ ORDER BY name ASC, country ASC

const sortOne = R.sortWith([
  R.ascend(propName),
  R.ascend(propCountry),
]);

sortone

@orther
Copy link
Author

orther commented Jan 27, 2017

sortTwo ~ ORDER BY country ASC, name ASC

const sortTwo = R.sortWith([
  R.ascend(propCountry),
  R.ascend(propName),
]);

sorttwo

@orther
Copy link
Author

orther commented Jan 27, 2017

sortThree ~ ORDER BY LENGTH(state) DESC, country ASC

const sortThree = R.sortWith([
  R.descend(R.compose(R.length, propName)),
  R.ascend(propCountry),
]);

sortthree

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