简体   繁体   English

如何排序对象数组?

[英]How to sort an array of objects?

I have an array of objects: 我有一个对象数组:

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",

}];

and a sorting order array constructed out of the object item titles. 以及由对象项标题构成的排序顺序数组。

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

how do I sort the first array by the order array so that the new data turns out like this 我如何按顺序数组对第一个数组进行排序,以便新数据像这样

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",

}];

?

Not same as ref post. 与参考文章不同。 I am sorting by a specific order array without any specific logic. 我按没有任何特定逻辑的特定顺序数组进行排序。

You could use an object as hash table 您可以将对象用作哈希表

{
    "Post with builder": 0,
    "All pages": 1,
    "Blog Categories": 2,
    "Single Blog Posts": 3
}

for the indices and sort with them. 索引并对其进行排序。

 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", }], order = ["Post with builder", "All pages", "Blog Categories", "Single Blog Posts"], orderObject = {}; order.forEach(function (a, i) { orderObject[a] = i; }) data.sort(function (a, b) { return orderObject[a.title] - orderObject[b.title]; }); document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>'); 

Since you already have the order arrays indexes for your ordering reference as a kind of hash, we may very simply use them like; 由于您已经将订购数组索引作为一种哈希值用于订购参考,因此我们可以像这样简单地使用它们:

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

// Using loadash //使用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"]; var order = [“带有构建器的帖子”,“所有页面”,“博客类别”,“单个博客帖子”];

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM