How to sort multi-array / nested map by value (e.g. from Firestore) in JavaScript

Tags: , ,



I’m trying to get a multi-array / nested map sorted by value via JavaScript / TypeScript.

My array currently looks like this:

let array =
    [
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'C'
        }
      },
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'B'
        }
      },
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'A'
        }
      }
    ];

Now I’d like to sort by the ['information']['name'] values like this:

let array_sorted =
    [
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'A'
        }
      },
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'B'
        }
      },
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'C'
        }
      }
    ];

Does anybody know how to do that? I’m especially struggling with the nested stuff…

Thank you in advance!

Answer

Using String.prototype.localeCompare, you can compare the string values and based on that result, using Array.prototype.sort function, you can sort the arrays as follows.

let array = [{
    classification: {
      company_id: 1
    },
    information: {
      name: 'C'
    }
  },
  {
    classification: {
      company_id: 1
    },
    information: {
      name: 'B'
    }
  },
  {
    classification: {
      company_id: 1
    },
    information: {
      name: 'A'
    }
  }
];

const result = array.sort((a, b) => a.information.name.localeCompare(b.information.name));
console.log(result);


Source: stackoverflow