0

I found this method, with which I have ordered the hours what I store in my records, I wanted them to be sorted from highest to lowest, but when I test the code, I notice that only two values of the array are compared, which are the first registers.

I've seen other methods of comparison and the logic is the same, what am I doing wrong? I group the messages per user, using the id of the user as key of the array , then I save the rest of data. I do this for retrieve the current messages, since I want show a list of the last currently messages sent.

This is the code:

var ref = new Firebase('https://chatfbexample.firebaseio.com/all-messages');
ref.on("value", function (snapshot) {
    var Messages = [];
    var value = 0;
    snapshot.forEach(function (snap) {
        value = snap.val().id;
        fecha = snap.val().id;
        Messages[value] = [];
        Messages[value]['fecha'] = snap.val().fechahora; //I receive a date with the format HH:MM:SS
        Messages[value]['texto'] = snap.val().texto;

    });

    function compare(a, b) {
        var time1 = a['fecha'].replace(/:/gi, '1');
        var time2 = b['fecha'].replace(/:/gi, '1');
        var data1 = parseInt(time1);
        var data2 = parseInt(time2);

        // alert(time1);
        if (data1 > data2)
            return -1;
        if (data1 < data2)
            return 1;
        return 0;
    }
    Messages.sort(compare);

    for (var i in Messages) {
        console.log("Hour: " + Messages[i]['fecha'] + ' ' + ' Message:  ' + Messages[i]['texto']);
    }
});

the result is something like this

Hour: 12:11:13 Message: whats'up?
Hour: 11:38:44 Message: p
Hour: 11:49:01 Message: hey?

the second and the third messages are not being compared

an image of my Firebase database

enter image description here

AL.
  • 36,815
  • 10
  • 142
  • 281
Felipe Castillo
  • 536
  • 8
  • 25
  • 1
    Your messages is not an array, it's an object. – Mathew Berg Jan 11 '17 at 12:42
  • hi Mathew, yes, I read about that, but, for some reason the ordering works, only for the two first elements, how can I resolve this?, I must convert the object in an array to can manage it? – Felipe Castillo Jan 11 '17 at 12:48
  • Could you provide some sample data of your Firebase database? – Rodrigo Ehlers Jan 11 '17 at 14:14
  • hi @hotrod I edited the post and upload an image of the database, you can see it now, only has three records, but grouped by id. – Felipe Castillo Jan 11 '17 at 14:33
  • Do you want your messages to be sorted from newest to oldest? – Rodrigo Ehlers Jan 11 '17 at 14:38
  • You've included a picture of the JSON tree in your question. Please replace that with the actual JSON as text, which you can easily get by clicking the Export JSON link in [your Firebase Database console](https://console.firebase.google.com/project/_/database/data/). Having the JSON as text makes it searchable, allows us to easily use it to test with your actual data and use it in our answer and in general is just a Good Thing to do. – Frank van Puffelen Jan 11 '17 at 14:51

2 Answers2

0

Instead of ordering client-side, you'll be better off asking the server to sort the messages:

ref.orderByChild("fechahora").on(...

Make sure that you define the proper index in your Firebase security rules:

{
  "rules": {
    "all-messages": {
      ".indexOn": "fechahora"
    }
  }
}

Without that the sorting will still work, but will happen on the client instead of the server.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

First off it probably would be better for you to save a timestamp from Firebase instead of an actual time, which was probably created on the client side, inside your database. This way you could easily let Firebase handle the sorting.

You would need to use firebase.database.ServerValue.TIMESTAMP to save the exact time at which Firebase received your message inside fechahora.

Following you could simply query all of your messages ordered by their child fechahora.

ref.orderByChild("fechahora").on("value", function (snapshot) {
    //Do stuff with your already sorted data
}

If you want your query to have a better performance set the .indexOn property of your node containing all the messages inside your Firebase Database rules to fechahora.

Bonus: If you want your data to be ordered newest to oldest instead of oldest to newest, you just need to use the negative value of the timestamp created by Firebase.

Rodrigo Ehlers
  • 1,830
  • 11
  • 25
  • thanks hotrod,I actually decided to work this way because the firebase only arrange the data from the oldest to the newest, I read about the timestamp but I do not understand the negative value, how can I get it? – Felipe Castillo Jan 11 '17 at 16:44
  • great, I have marked the answer, your question is this? http://stackoverflow.com/questions/41576725/firebase-use-endat-if-timestamp-field/41577170#41577170 – Felipe Castillo Jan 11 '17 at 19:05
  • No, it is this: http://stackoverflow.com/questions/41594643/correctly-sort-nodes-from-newest-to-oldest check out my `prepareUpload()` method. It is written in `Java` but I guess you will still be able to see what I am doing there. – Rodrigo Ehlers Jan 11 '17 at 19:10