Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an Array of JavaScript Objects a Specific Order (using existing function)

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:

  • Javascript - sort array based on another array - Stack Overflow
  • javascript - How do I sort an array of objects based on the ordering of another array? - Stack Overflow

Similar/related questions:

  • Sorting an Array of Objects in PHP In a Specific Order
  • php - Sort array of objects
like image 698
mkopala Avatar asked Sep 17 '13 20:09

mkopala


People also ask

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.

Can you sort an array of objects in JavaScript?

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.

What is the correct method to use in JavaScript sorting arrays?

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.


1 Answers

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)

like image 70
McGarnagle Avatar answered Sep 19 '22 05:09

McGarnagle