How to use the orderByChild() function in Firebase

Let's suppose that we have an object in Firebase with the following properties:

jsx
  "projects" : {
    "-LvVEICa_n5urHfy5xp1" : {
      "Description" : "Thai community among other things.",
      "Language" : "Es",
      "Link" : "nomoresheet.es",
      "Name" : "Nomoresheet",
      "Status" : "Active",
      "Year" : 2015
    },
    "-Lv_3o81bPobit0od0ea" : {
      "Description" : "Application to track time",
      "Language" : "En",
      "Link" : "-",
      "Name" : "Tiempone",
      "Status" : "In progress",
      "Year" : 2019
    },
    "-Lw230jEs96hUoCYzQ3J" : {
      "Description" : "Personal space to share things I learn",
      "Language" : "En",
      "Link" : "erikmartinjordan.com",
      "Name" : "Erikmartinjordan",
      "Status" : "Active",
      "Year" : 2017
    }

If we want to sort the object by the Year property, we need to call the orderByChild() function.

jsx
// Getting projects data from Firebase
firebase.database().ref('projects').orderByChild('Year').on('value', snapshot => {

    // Defining empty array
    let array = [];

    // Pushing new component for each child
    snapshot.forEach(child => {

        // Getting child object info
        let childObject = child.val();

        // Adding object to array
        array = [...array, childObject]

    });
    
    // array is sorted after this point
    // ...

});

Hint: executing orderByChild() and getting snapshot.val() is a wrong approach, because snapshot.val() returns an object. Order of object elements depends on the browser.

Instead, using the orderByChild() function guarantees the order of the childs in the snapshot array. After we get this array, we can iterate over each child.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.