Tuesday, 17 September 2013

Sorting an Array of JavaScript Objects a Specific Order

Sorting an Array of JavaScript Objects a Specific Order

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) 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

No comments:

Post a Comment