Given an array of objects:
{ key: "a", value: 42 }, { key: "d", value: 28 }, { key: "c", value: 92 }, { key: "b", value: 87 }
and an array of keys:
["c", "a", "b", "d"]
Is there a ECMAScript function or a 3rd-party JavaScript library that lets you sort - in one line/function call - the first array of objects, to match the order of the keys specified in the second array, such that the result is:
{ key: "c", value: 92 }, { key: "a", value: 42 }, { key: "b", value: 87 }, { key: "d", value: 28 }
Other questions that provide a function or algorithm:
Similar/related questions:
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.
Sort an Array of Objects in JavaScriptTo sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
Just use indexOf
to convert the key to the correct order:
var order = ["c", "a", "b", "d"]; _.sortBy(arr, function(obj){ return _.indexOf(order, obj.key); });
Fiddle
If there are a lot of keys, then it would be advantageous to make a hash-map out of the array, like:
var order = ["c", "a", "b", "d"]; var orderMap = {}; _.each(order, function(i) { orderMap[i] = _.indexOf(order, i); });
This makes the key-sorting lookup constant time rather than O(n). (Fiddle)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With