Javascript中的自定义排序数组

时间:2018-07-24 15:43:59

标签: javascript arrays sorting

假设我有以下数组:

[
    {
       "key":"Certified?",
       "value":"Yes"
    },
    {
       "key":"Language",
       "value":"EN"
    },
    {
       "key":"Training-Place",
       "value":"City"
    }
 ]

我想按LanguageCertified?Training-Place的特定顺序对其进行排序,我该如何实现呢?最好我可以像这样定义排序:

["Language", "Certified?", "Training-Place"]

非常感谢,感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

创建一个包含订单的数组。现在遍历此数组,并从主数组中过滤出与名称匹配的对象

let arrayToSort = [{
    "key": "Certified?",
    "value": "Yes"
  },
  {
    "key": "Language",
    "value": "EN"
  },
  {
    "key": "Training-Place",
    "value": "City"
  }
]


let sortOrder = ["Language", "Certified?", "Training-Place"]
let customSortArray = [];
sortOrder.forEach(function(item) {
  customSortArray.push(
    arrayToSort.filter(function(items) {
      return item === items.key
    })[0])
})


console.log(customSortArray)

答案 1 :(得分:1)

您可以简单地使用Arrays.sort()并使用order数组对订单数组指定的顺序进行排序。

尝试以下操作:

var arr = [ { "key":"Certified?", "value":"Yes" }, { "key":"Language", "value":"EN" }, { "key":"Training-Place", "value":"City" }, { "key":"Training-Place", "value":"aaa" }, { "key":"Language", "value":"bbb" }];

var order = ["Language", "Certified?", "Training-Place"];
 
 arr.sort((a,b)=> order.indexOf(a.key) - order.indexOf(b.key));
 
 console.log(arr);