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

倾然丶 夕夏残阳落幕 提交于 2019-12-17 17:36:12

问题


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

回答1:


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)




回答2:


Great answers provided so far. Thought that the following may also be an alternative solution in plain JS:

var arr = arr.sort(function(a,b) {
    return order.indexOf( a.key ) > order.indexOf( b.key );
    //for the sake of recent versions of Google Chrome use:
    //return a.key.charCodeAt(0) > b.key.charCodeAt(0); or return a.key.charCodeAt(0) - b.key.charCodeAt(0);
});

var arr = [
    {
        key: "a",
        value: 42
    },
    {
        key: "d",
        value: 28
    },
    {
        key: "c",
        value: 92
    },
    {
        key: "b",
        value: 87
    }
];

var order = ["c", "a", "b", "d"];

console.log( 'Original: ', JSON.stringify( arr ) );

var arr = arr.sort(function(a,b) {
      return order.indexOf( a.key ) > order.indexOf( b.key );
});

console.log( 'Ordered: ', JSON.stringify( arr ) );



回答3:


I can't claim that this is the most efficient way, but you can use the key for each object as a key for properties in another object. Then simply access them by these keys.

for (x = 0; x < objn.length; x++) {
    newobj[objn[x].key] = objn[x];
}
objn = [];
for (x = 0; x < keys.length; x++) {
    objn.push(newobj[keys[x]]);
}
console.log(objn);

http://jsfiddle.net/WdehF/




回答4:


// create hash map el.key -> index, to help us with direct access, avoid searching
const hashMap = arr.reduce((acc, el, index) => { acc[el.id] = el; return acc }, {})

// finally, map the ids to the final result
const ids.map(id => hashMap[id])


来源:https://stackoverflow.com/questions/18859186/sorting-an-array-of-javascript-objects-a-specific-order-using-existing-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!