如何对对象数组进行排序?

时间:2016-04-09 12:19:37

标签: javascript arrays sorting

我有一个对象数组:

var data= [{
    "title": "All pages",
    "page": "all",

}, {
    "title": "Post with builder",
    "page": "pt_post_6188",

}, {
    "title": "Blog Categories",
    "page": "tx_category",

}, {
    "title": "Single Blog Posts",
    "page": "pt_post",

}];

以及由对象项标题构造的排序顺序数组。

var order = ["Post with builder", "All pages", "Blog Categories", "Single Blog Posts"];

如何按顺序数组对第一个数组进行排序,以便新数据如此

var newdata= [{
    "title": "Post with builder",
    "page": "pt_post_6188",

}, {
    "title": "All pages",
    "page": "all",

}, {
    "title": "Blog Categories",
    "page": "tx_category",

}, {
    "title": "Single Blog Posts",
    "page": "pt_post",

}];

与ref post不同。我按特定的顺序数组排序,没有任何特定的逻辑。

2 个答案:

答案 0 :(得分:0)

由于您已经将订购参考的订单数组索引作为一种哈希,我们可以非常简单地使用它们;

sorted = Array(order.length);
data.forEach((c,i) => sorted[order.indexOf(c.title)] = c);

答案 1 :(得分:0)

//使用loadash

var data= [{
"title": "All pages",
"page": "all",
}, {
"title": "Post with builder",
"page": "pt_post_6188",
}, {
"title": "Blog Categories",
"page": "tx_category",
}, {
"title": "Single Blog Posts",
"page": "pt_post",
}];

var order = [“Post with builder”,“All pages”,“Blog Categories”,“Single Blog Posts”];

function (data, order){
 return _.reduce(order, function (output, v) {
  output.push(_.filter(data,{title:v})[0]);
  return output;
 },[]);
}