Benn
Benn

Reputation: 5023

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.

Upvotes: 0

Views: 85

Answers (3)

Devank
Devank

Reputation: 159

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

Upvotes: 0

Redu
Redu

Reputation: 26191

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);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386786

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>');

Upvotes: 1

Related Questions