简体   繁体   中英

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

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;
 },[]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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