Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of objects based on another array of ids

I have 2 arrays

a = [2,3,1,4]
b = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]

How do I get b sorted based on a? My desired output would be

c = [{id: 2}, {id: 3}, {id: 1}, {id: 4}]

I would prefer to use Ramda or regular JS.

like image 769
ABC Avatar asked Feb 21 '16 16:02

ABC


People also ask

How do you sort an array of objects based on the key value?

To sort array on key value with JavaScript, we can use the array sort method. to call arr. sort with a callback that sort the entries by the name property lexically with localeCompare .

How do you sort an array by id?

IF you mean that you wanted them sorted by id and if the id matches, you want them sorted by name then use this: items. sort(function(a, b) { if (a.id !== b.id) { return a.id - b.id } if (a.name === b.name) { return 0; } return a.name > b.name ?

How do you sort an array in a specific order?

Sorting an array of objects in javascript is simple enough using the default sort() function for all arrays: const arr = [ { name: "Nina" }, { name: "Andre" }, { name: "Graham" } ]; const sortedArr = arr.


2 Answers

Ramda really shines for these types of problems.

Where the size of the data is small, we can use a simple reduce function, and indexOf helper.

// 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 } ]

This works well for small(ish) data sets but the indexOf operation on every iteration through the reduction is inefficient for large data sets.

We can remedy this by tackling the problem from the other side, lets use groupBy to group our objects by their id, thus creating a dictionary lookup (much better!). We can then simply map over the required indexes and transform them to their corresponding object at that position.

And here is the solution using this approach:

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 } ]

Finally, this is yet another solution, which is very succinct:

R.sortBy(R.pipe(R.prop('id'), R.indexOf(R.__, a)))(b);
// [ { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 } ]

I love the way you can compose functions with behaviour and separate the algorithm from the data upon which it acts using Ramda. You end up with very readable, and easy to maintain code.

like image 43
arcseldon Avatar answered Sep 21 '22 13:09

arcseldon


You can provide a custom comparison function to JavaScript's Array#sort method.

Use the custom comparison function to ensure the sort order:

var sortOrder = [2,3,1,4],
    items     = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];

items.sort(function (a, b) {
  return sortOrder.indexOf(a.id) - sortOrder.indexOf(b.id);
});

MDN:

  • If compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first).
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).

Hitmands made a very fair comment on the above solution:

This approach is O(n2), and would cause performance issues in big sized lists. Better to buiild the dictionary first, so that it stays O(n)

Consequently, the above solution might end up not being as fast as you need on large inputs.

To implement Hitmands' suggestion:

let sortOrder = [2,3,1,4],
    items     = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];

const itemPositions = {};
for (const [index, id] of sortOrder.entries()) {
  itemPositions[id] = index;
}

items.sort((a, b) => itemPositions[a.id] - itemPositions[b.id]);
like image 183
theonlygusti Avatar answered Sep 21 '22 13:09

theonlygusti