-2

This is the JSON data i am fetching from POSTMAN. I want it to be ordered in a nearest to todays date. I tried many angular pipes but unfortunately nothings working. Any help would be great. I want to sort the date by the "broadcastOn" field. Thanks in advance.

[ {
        "messageId": "09ca0609-bde7-4360-9d3f-04d6878f874c",
        "broadcastOn": "2018-02-08T11:06:05.000Z",
        "message": "{"title":"Server Side Test 2","text":"Different Message again","image":"https://api.adorable.io/avatars/285/abott@adorable.png","url":"https://www.google.co.in"}"
    },
    {
        "messageId": "0a5b4d0c-051e-4955-bd33-4d40c65ce8f7",
        "broadcastOn": "2018-02-08T10:36:27.000Z",
        "message": "{"title":"Broadcast","text":"Broadcast","image":"https://api.adorable.io/avatars/285/abott@adorable.png","url":"https://www.google.co.in"}"
    },
    {
        "messageId": "0a98a3f3-aa30-4e82-825a-c8c7efcef741",
        "broadcastOn": "2018-02-08T11:45:00.000Z",
        "message": "{"title":"Me sending the message","text":"Me sending the message","image":"https://api.adorable.io/avatars/285/abott@adorable.png","url":"https://www.google.co.in"}"
    },
    {
        "messageId": "0cb4e30f-756a-4730-a533-594ddcd45335",
        "broadcastOn": "2018-02-08T11:01:57.000Z",
        "message": "{"title":"Server Side Test","text":"Different Message","image":"https://api.adorable.io/avatars/285/abott@adorable.png","url":"https://www.google.co.in"}"
    }
]

Im adding a snippet from the service section as well for your reference..

addMessage(message) {
    let header: Headers = new Headers();
        header.append('Authorization', 'bearer' + this.authservice.getAccessToken());
        let options = new RequestOptions({headers: header});
    this.sent.push(message);
        return this.http.post('https://sexhops8j5.execute-api.us-west-2.amazonaws.com/dev/notifications/broadcast', message, options)
        .map(response => 
            { 
                    return response.json();  
            });     
    }
    getMessage(){
        let header: Headers = new Headers();
        header.append('Authorization', 'bearer' + this.authservice.getAccessToken());
        let options = new RequestOptions({headers: header});
        return this.http.get('https://sexhops8j5.execute-api.us-west-2.amazonaws.com/dev/notifications/sent', options)
        .map(response => {
            let message=[];
            for(let item of response.json()){
                let parsedMessages = JSON.parse(item.message);
                message.push({...parsedMessages, BroadcastOn: item.broadcastOn,MessageId: item.messageId});
            }
            console.log(message);
                            return message;


        });
    }

I'm adding a snippet of the .ts file as well

  sendMessage(form){
   this.messageService.addMessage({message:this.form.value.string, title:this.form.value.titleText, url:this.form.value.imageurl, image:this.form.value.image, broadcastOn:this.date})
   .subscribe(message => { this.getSentMessages();console.log(message);}
     );
    this.message = ''; 
    this.inputImage='';
    this.inputTitle='';
    this.inputString='';
    this.inputUrl='';
  }
  getSentMessages(){
    this.messageService.getMessage()
    .subscribe(message => {this.sentMessages = message});
  }
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
abhijith
  • 117
  • 6
  • 17

2 Answers2

3

It's not necessary lodash, nor moment. broadcastOn is a string. The date is yyy-mm-ddTHH:mm, so, if a date is bigger that other, the string is bigger that other

getSentMessages(){
    this.messageService.getMessage()
    .subscribe(message => {
     this.sentMessages = message.sort((a,b)=>{
           return a.broadcastOn==b.broadcastOn?0
                 :a.broadcastOn>b.broadcastOn?1:-1
      }));
     });
  }
Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • Appreciate your help can please tell me where i should add your code Since I'm new to Angular 4 – abhijith Feb 21 '18 at 09:15
  • in subscribe you have a local variable "message", that is your messages. So, after received, save in this.message the messages sorted – Eliseo Feb 21 '18 at 10:22
  • Is this what you are saying?? getSentMessages(){ this.messageService.getMessage() .subscribe(message => {this.sentMessages = message.sort((a,b)=>{ return a.broadcastOn==b.broadcastOn?0 :a.broadcastOn>b.broadcastOn?1:-1 })}); } – abhijith Feb 21 '18 at 10:32
  • I got it thanks a ton. I misspelled a word and hence I was not getting.. Thanks a lot you just made my day.. – abhijith Feb 21 '18 at 11:05
  • what should I do so as to print them in descending order?? – abhijith Feb 21 '18 at 11:07
  • @abhijith, if you want to sort in reverse order, you change the "sort function" return a.broadcastOn==b.broadcastOn?0 :a.broadcastOn>b.broadcastOn?-1:1. The "sort function" must be return 0 if two elements are equals, and 1 or -1 depending if the first element have to be first or not – Eliseo Feb 21 '18 at 11:22
0

With help of lodash and moment you can do it like this :

var sortedMessages = _.sortBy(messages, function(o) { return  
    moment(o.broadcastOn); 
}).reverse();

//OR (With ES6 way)

var sortedMessages = _.sortBy(messages,(o) => moment(o.broadcastOn) ).reverse();

WORKING DEMO (Angular 5)

var messages = [ {
        "messageId": "09ca0609-bde7-4360-9d3f-04d6878f874c",
        "broadcastOn": "2018-02-08T11:06:05.000Z",
        "message": {"title":"Server Side Test 2","text":"Different Message again","image":"https://api.adorable.io/avatars/285/abott@adorable.png","url":"https://www.google.co.in"}
    },
    {
        "messageId": "0a5b4d0c-051e-4955-bd33-4d40c65ce8f7",
        "broadcastOn": "2018-02-08T10:36:27.000Z",
        "message": {"title":"Broadcast","text":"Broadcast","image":"https://api.adorable.io/avatars/285/abott@adorable.png","url":"https://www.google.co.in"}
    },
    {
        "messageId": "0a98a3f3-aa30-4e82-825a-c8c7efcef741",
        "broadcastOn": "2018-02-08T11:45:00.000Z",
        "message": {"title":"Me sending the message","text":"Me sending the message","image":"https://api.adorable.io/avatars/285/abott@adorable.png","url":"https://www.google.co.in"}
    },
    {
        "messageId": "0cb4e30f-756a-4730-a533-594ddcd45335",
        "broadcastOn": "2018-02-08T11:01:57.000Z",
        "message": {"title":"Server Side Test","text":"Different Message","image":"https://api.adorable.io/avatars/285/abott@adorable.png","url":"https://www.google.co.in"}
    }
]

var sortedMessages = _.sortBy(messages, function(o) { return  moment(o.broadcastOn); })
.reverse();

console.log(sortedMessages);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • thanks brother. The array of JSON data is coming from the backend. Since I'm new to angular I don't know where to add the code snippet which you sent should i include it in the .ts file or in the .service file. Thanks in advance – abhijith Feb 21 '18 at 05:10
  • The scripts which you sent where should I include it. I'm working in Angular 4 – abhijith Feb 21 '18 at 05:11
  • @abhijith , then you gonna learn something new today , read this https://stackoverflow.com/questions/34660265/importing-lodash-into-angular2-typescript-application – Vivek Doshi Feb 21 '18 at 05:13
  • Thanks @Vivek i went through the process which you sent can you please tell me how can i use it without reverse function. – abhijith Feb 21 '18 at 05:23
  • remove `reverse` it's just JavaScript function – Vivek Doshi Feb 21 '18 at 05:26
  • This is my .ts file@Vivek sendMessage(form){ this.messageService.addMessage({message:this.form.value.string, title:this.form.value.titleText, url:this.form.value.imageurl, image:this.form.value.image, broadcastOn:this.date}) .subscribe(message => { this.getSentMessages();console.log(message);} ); this.message = ''; this.inputImage=''; this.inputTitle=''; this.inputString=''; this.inputUrl=''; } getSentMessages(){ this.messageService.getMessage() .subscribe(message => {this.sentMessages = message}); } – abhijith Feb 21 '18 at 05:29
  • Hey @Vivek where should i add this code var sortedMessages = _.sortBy(messages,(o) => moment(o.broadcastOn) ).reverse(); – abhijith Feb 21 '18 at 06:15
  • within `getSentMessages` function instead of `this.sentMessages = message` put `this.sentMessages = _.sortBy(message,(o) => moment(o.broadcastOn) ).reverse();` – Vivek Doshi Feb 21 '18 at 06:27
  • you have to follow the same steps as you have follow for the lodash to install momnet – Vivek Doshi Feb 21 '18 at 06:50
  • i added moment but the output which I'm seeing doesn't seem to be sorted... Anyways thanks a lot for your help. – abhijith Feb 21 '18 at 06:51
  • @abhijith , code is 100% correct , as you can check that by running the snippet , all you need is to implement in Angular way – Vivek Doshi Feb 21 '18 at 06:52
  • @abhijith , please check https://stackblitz.com/edit/angular-lodash-momet – Vivek Doshi Feb 21 '18 at 07:03
  • getSentMessages(){ this.messageService.getMessage() .subscribe(message => {this.sentMessages = _.sortBy(message,(o) => moment(o.broadcastOn) ).reverse();}); } Iadded like this – abhijith Feb 21 '18 at 07:13
  • neither i am getting an error nor my problem is getting solved... Anyways thanks @Vivek. – abhijith Feb 21 '18 at 07:45
  • @abhijith , Create a demo just like me , then I can help furthure , Please also upvote/accept the answer as you like – Vivek Doshi Feb 21 '18 at 08:04
  • Thanks a ton @Vivek.. I had misspelled a word and hence was not getting the output.. I have upvoted.. Thank you once again – abhijith Feb 21 '18 at 11:13
  • @abhijith , Glad to know , please accept the answer :D – Vivek Doshi Feb 21 '18 at 11:18