0

Hey i'm learning how to work with JS and firebase. My problem my orders gets loaded at random and i always want it to sorted by time. I've tried sorting the data from firebase but it still comes in at random.

Iv'e looked at a couple of things regarding sorting my map called "rows" but can't seem to implement it in any reasonable way.

This is how i tried sorting my firebase db before getting it at my order page

// route for database 
router.get("/orderslist", (req, res) => {    

  let orders = []
  let number_of_orders

    // Getting the snapshot of the order collection
    db.collection('orders').orderBy('time').get().then( productSnapshot => {
      number_of_orders = productSnapshot.size

      // iterating over the order snapshot
      productSnapshot.forEach(orderDoc => {

        // creating an order object and assigning the ID and the rest of the information from the database
        var order = {
          id: orderDoc.id,
          customer_name: orderDoc.data().customer_name,
          date: orderDoc.data().date,
          comments: orderDoc.data().comments,
          time: orderDoc.data().time,
          total: orderDoc.data().total,
          order_status: orderDoc.data().order_status,
          products: []
        }
        // using the id, to get the products from the subcollection
        db.collection('orders/' + order.id + '/products').get().then( productSnapshot => {

          // iterating over the product snapshot
          productSnapshot.forEach(productDoc => {

            // creating a product object
            var product = {
              name: productDoc.data().name,
              price: productDoc.data().price
            }

            // then we push the product object to the list of products in the order object
            order.products.push(product)

          });

          // we are finished iterating over the productsnapshot and now we can push it to the orders list
          orders.push(order)

          // checks if the list is filled with everything from the database
          if(orders.length == number_of_orders){
            return res.json(orders)
          }

        });

      });

  });

});

This is my json input

[
  {
    "id": "s2hym8IVa10pEgtgmmq9",
    "customer_name": "Mikkel",
    "date": "13/05-2020",
    "comments": "",
    "time": 1050,
    "total": 40,
    "order_status": true,
    "products": [
      {
        "name": "Latte",
        "price": 40
      }
    ]
  },
  {
    "id": "xWmlB9fHD4rw8Di75llp",
    "customer_name": "Emil",
    "date": "07/05-2020",
    "comments": "without sugar",
    "time": 1211,
    "total": 40,
    "order_status": false,
    "products": [
      {
        "name": "Latte",
        "price": 40
      }
    ]
  },
  {
    "id": "ggYSVKA1i0U8khIpeud4",
    "customer_name": "Oliver",
    "date": "01/05-2020",
    "comments": "order to be packed neatly because im on a bike",
    "time": 1450,
    "total": 38,
    "order_status": false,
    "products": [
      {
        "name": "Latte Macchiato",
        "price": 38
      }
    ]
  },
  {
    "id": "pq62yo42KS41VgeGGiZX",
    "customer_name": "Naida",
    "date": "07/05-2020",
    "comments": "nope",
    "time": 1257,
    "total": 40,
    "order_status": true,
    "products": [
      {
        "name": "Latte",
        "price": 40
      }
    ]
  },
  {
    "id": "p2dKspiU535P29Gex6Uz",
    "customer_name": "Alper",
    "date": "13/05-2020",
    "comments": "",
    "time": 1937,
    "total": 40,
    "order_status": false,
    "products": [
      {
        "name": "Latte",
        "price": 40
      }
    ]
  }
]

This is my orderpage JS

  // jquery getting our json order data from API
    $.get("http://localhost:8888/orderslist", (data) => {    


        // loops through our orderlist api
        let rows = data.map(item => {
          let $clone = $('#frontpage_new_ordertable tfoot tr').clone();
          $clone.data("id", item.id);
          $clone.find('.customer_name').text(item.customer_name);
          $clone.find('.date').text(item.date);
          $clone.find('.time').text(item.time);
          $clone.find('.pickup').text(item.pickup);
          $clone.find('.comments').text(item.comments);
          $clone.find('.total').text(item.total + ' Kr.');


          // accept and cancel buttons
          $clone.find('.order_status').html(
            `<button class="acceptOrder" type="button">Accept</button>` + 
            `<button class="cancelOrder" type="button">Cancel</button>`
          );

          // loops through orders product name
          let productsName = item.products.map(prod => `${prod.name}`);
          $clone.find('.products').html(productsName.join('<br />'));

          // loops through orders product price
          let productsPrice = item.products.map(prod => `${prod.price} Kr.`);
          $clone.find('.price').html(productsPrice.join('<br />'));

          return $clone;
        });


        //appends to our frontpage html 
        $("#frontpage_new_ordertable tbody").append(rows);
    });

});
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
FakeRune
  • 63
  • 1
  • 3
  • 13
  • You only show a single object. To sort something i would expect an array of objects. Could you please include the data you get from firebase? – Moritz Roessler May 26 '20 at 13:29
  • 4
    *"I've tried sorting from data from firebase but still no luck."* Please show us that. There's nothing in the code in the question that's sorting or seemingly trying to sort anything. – T.J. Crowder May 26 '20 at 13:30
  • Likely answered here: https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values – T.J. Crowder May 26 '20 at 13:31
  • @T.J.Crowder added the firebase js and rest of my json data – FakeRune May 26 '20 at 13:45
  • Does this answer your question? [Sorting an array of objects by property values](https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values) – bill.gates May 26 '20 at 13:50
  • @FakeRune - I still don't see anything that attempts to sort the data. Please refer to [the question I linked earlier](https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values), this would appear to be a duplicate of that question (and many others).. You can find them by doing [this search](/search?q=%5Bjs%5D+sort+array+of+objects). More about searching [here](/help/searching). – T.J. Crowder May 26 '20 at 13:51
  • 1
    If I'm not mistaken, Firebase provides ordering natively, before it even gets to an array of objects. In fact, you've already got a `.orderBy('time')` call on your retrieval of `orders`. If you want to sort the products, simply add a `.orderBy('property')` previous to the `get()` call there. Or however it works; I'm no Firebase expert. But I would hope that sorting it in Firebase, natively, would be faster, or at least as fast as, sorting it afterwards. – Heretic Monkey May 26 '20 at 13:57
  • @HereticMonkey - Ah, I didn't look in the Firebase code, and should have. Yeah, almost certainly want to fix it there rather than once it gets to the client. Unlikely to be *slower* (though...I guess on the client means less load for the server vs. not ordering it at all on the server...). – T.J. Crowder May 26 '20 at 14:04
  • @T.J.Crowder The link seems like the right path but i can't get my head around how to implement it. On another note i've tried looking through the firebase documentation with the ``.orderBy`` but to no success as to why it dosen't work – FakeRune May 26 '20 at 19:31
  • If you can't get the Firebase side figured out, you can sort it after it arrives at the browser using the answers to the [question I linked earlier](https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values), except in your case `time` is already a number so you don't have to parse it: `data.sort(function(a, b) { return a.time - b.time; });` (that sorts ascending; to sort descending, swap `a` and `b`). – T.J. Crowder May 26 '20 at 21:01

2 Answers2

0

You can try this

const rows = [{time: 1}, {time: 1050}, {time: 238}, {time: 9999}]

//sorted result
rows.sort((a,b) => a.time - b.time)
tcf01
  • 1,699
  • 1
  • 9
  • 24
  • 1
    Sorting an array of objects by object property is a ***very*** common duplicate question, and has answers in many, many previous forms, such as [here](https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values) (as I mentioned in a comment). Please don't post answers to obvious duplicates. – T.J. Crowder May 26 '20 at 13:49
-1

I believe this is what you are looking for: data.sort

Ex. (function to sort)

data.sort((a,b)=>{
  return (a.date > b.date)
})

This will only work if item.date is a Date Object.

For creating date object you can use: new Date(item.date)

PS. you can flip this > sign with < to change the order

Sankalp Bhamare
  • 523
  • 3
  • 7
  • 1
    Sorting an array of objects by object property is a ***very*** common duplicate question, and has answers in many, many previous forms, such as [here](https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values) (as I mentioned in a comment). Please don't post answers to obvious duplicates. – T.J. Crowder May 26 '20 at 13:49