Skip to content

Instantly share code, notes, and snippets.

@413n
Last active September 16, 2020 10:41
Show Gist options
  • Save 413n/41d2ac6f35ca1b9768c3f584854f261c to your computer and use it in GitHub Desktop.
Save 413n/41d2ac6f35ca1b9768c3f584854f261c to your computer and use it in GitHub Desktop.
Sort an array of objects based on another array of ids using RAMDA
/*
Reference https://stackoverflow.com/a/35559392
Ramda is needed for this sort to work!
*/
// IMPORTS
import * as R from 'ramda';
// BACKGROUND
const a = [2,3,1,4];
const b = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
// SOLUTION #1
// match id of object to required index and insert
var sortInsert = function (acc, cur) {
var toIdx = R.indexOf(cur.id, a);
acc[toIdx] = cur;
return acc;
};
// point-free sort function created
var sort = R.reduce(sortInsert, []);
// execute it now, or later as required
sort(b);
// [ { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 } ]
// SOLUTION #2
var groupById = R.groupBy(R.prop('id'), b);
var sort = R.map(function (id) {
return groupById[id][0];
});
sort(a);
// [ { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 } ]
// SOLUTION #3
R.sortBy(R.pipe(R.prop('id'), R.indexOf(R.__, a)))(b);
// [ { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment