Reputation: 31
I've generated some news items from a laravel API output, i display these on a angular 4 cli project. I noticed the items aren't on descending order though and I'm trying to fix this on the client side. Check it out, this is what I've got.
This is my JSON output from the api:
{
"post": [
{
"id": 17,
"creator": null,
"title": "Test artikel 4",
"content": "<p>Dit is een test artikel voor het nieuws.</p>",
"tags": null,
"photo": "website/uploads/",
"sticky": 0,
"created_at": 1506000062,
"updated_at": false,
"category": ""
},
{
"id": 20,
"creator": null,
"title": "Test artikel 3",
"content": "<p>Dit is een test. Geen sticky.</p>",
"tags": null,
"photo": "website/uploads/",
"sticky": 0,
"created_at": 1506345662,
"updated_at": false,
"category": ""
},
{
"id": 23,
"creator": null,
"title": "Hovenier 2",
"content": null,
"tags": null,
"photo": "website/uploads/1505990708_Verboon Hoveniers.jpg",
"sticky": 0,
"created_at": 1506432062,
"updated_at": false,
"category": "Test categorie 1"
}
]
}
As you can see, there is a created_at object in the array based on a unix timestamp. What I'm trying to do is sort these items based on that created_at object using angular 4 typescript.
I've tried the sort() function, but I can't seem to get it to work.
Can anyone tell what is the best way to tackle this problem? I think it must be something really simple, but I can't seem to get it.
Thanks!
edit: I have placed it in a variable, but I get this: ERROR TypeError: Cannot read property 'sort' of undefined
also, this is the console.log from the variable.
Upvotes: 2
Views: 623
Reputation: 2650
Store your data in a variable, then sort the post
property of your json object
var items = {your jsons}
items.post.sort((a,b) => a.created_at - b.created_at)
Upvotes: 1
Reputation: 242
You need to do something like this.
yourObjectName.post.sort(function(a, b) {
return a.created_at - b.created_at;
});
Upvotes: 1
Reputation: 1176
Maybe this code can help you:
const {posts} = yourJSON;
posts.sort((a, b) => a.created_at - b.created_at);
Upvotes: 4
Reputation: 2085
Write the sort function like this.
var sortedPosts = data.post.sort((item1,item2) => item2.created_at - item1.created_at)
Upvotes: 1