2

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.

Console Log

4 Answers 4

4

Maybe this code can help you:

const {posts} = yourJSON;
posts.sort((a, b) => a.created_at - b.created_at);
Sign up to request clarification or add additional context in comments.

1 Comment

Is it posts variable or your JSON response? @CasvantWout
1

Write the sort function like this.

var sortedPosts = data.post.sort((item1,item2) => item2.created_at - item1.created_at)

Comments

1

You need to do something like this.

yourObjectName.post.sort(function(a, b) {
    return a.created_at - b.created_at;
});

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.