Sort array by name


#1

Hi Folks,

I am doing POC where i display contact details of the phone using ionic native contact plugin. Contact display is random there is no order.

How to sort them alphabetically, below is my code -

this.contacts.find(["displayName", "phoneNumbers"],
    {multiple: true, hasPhoneNumber: true }
    ).then((contacts) => {
      for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].displayName !== null) {
          var contact = {};
          contact["name"] = contacts[i].displayName;
          this.contactList.push(contact);
        }
      }
      this.groupContacts(this.contactList);
    });

This code above gives me contact names randomly , is there any way i can sort them.

Appreciated.


#2

try it :

 this.groupContacts = this.contactList.sort((a: any, b: any) => {
      if (a < b) {
        return -1;
      } else if (a > b) {
        return 1;
      } else {
        return 0;
      }
    });

#3

Didn’t work for me but @saidmrn thanks man. I got to solve this. :slightly_smiling_face: