根据预定义的顺序对对象数组进行排序

时间:2019-06-13 00:16:01

标签: javascript arrays algorithm object

如何根据预定义的顺序对对象数组进行排序?

例如,我希望订单为:['foot','bike','car','plane']

我有一个数组:

[{
    name: "car",
    color: "blue"
},
{ 
    name: "bike",
    color: "yellow"
},
{
    name: "plane",
    color: "red",
},
{
    name: "foot",
    color: 'black',
}]

2 个答案:

答案 0 :(得分:1)

您可以按照以下方式进行排序。

var baseobj = [{
    name: "car",
    color: "blue"
},
{ 
    name: "bike",
    color: "yellow"
},
{
    name: "plane",
    color: "red",
},
{
    name: "foot",
    color: 'black',
}]

var defined = ['foot','bike','car','plane'];

baseobj.sort(function (a,b){
  return defined.indexOf(a.name) - defined.indexOf(b.name)
});

console.log(baseobj);

答案 1 :(得分:0)

在排序中使用indexOf会将通常为O(nlogn)的排序变成具有二次复杂度的运算,因为您需要在order数组中搜索两次以进行排序中的每个比较。如果您的排序列表很小,那么这可能无关紧要,但是,如果您要对很多项目进行排序,则可以合理地创建一个排序术语到其各自索引的映射,以允许进行恒定时间查找。这将保留O(nlogn)排序的复杂性:

let order = ['foot','bike','car','plane']

// mapping name -> index
let orderMap = new Map(order.map((item, index) => [item, index]))

let arr = [{name: "car",color: "blue"},{ name: "bike",color: "yellow"},{name: "plane",color: "red",},{name: "foot",color: 'black',}]

// use mapping to determine sort order:
arr.sort((a, b) => orderMap.get(a.name) - orderMap.get(b.name))

console.log(arr)