Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting and Array alphabetically

I have an Array I am trying to sort alphabetically by the description, unfortunately it’s not doing anything.

I believe my code is right as it worked before, maybe I’m missing something basic but I can’t see it.

Here’s the array

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  status:200
    content:{
      records:[
        0:{
          id:"recCmTdywUZc3mRYr"
          createdTime:"2023-01-28T22:24:08.000Z"
          fields:{
            Description:"Apple"
            Qty:9
          }
        }
        1:{
          id:"recDg7dLnRsdwfvbc"
          createdTime:"2023-01-28T22:24:08.000Z"
          fields:{
            Description:"Orange"
            Qty:6
          }
        }
        2:{
          id:"recDhHyMIAS1qGu3E"
          createdTime:"2023-01-28T22:30:56.000Z"
          fields:{
            Description:"Pear"
            Qty:1
          }
        }
        3:{
          id:"recIMEr6bOtpS1Kdd"
          createdTime:"2023-01-28T22:30:55.000Z"
          fields:{
            Description:"Banana"
            Qty:10
          }
        }
      ]
    }
}

Here’s the code I’m using to sort the array:

sorted = inputArray.items.slice();
sorted.sort((a, b) => a. Description.localeCompare(b. Description))

>Solution :

Assuming records is an array, you need to get the right value with

const
    data = { status: 200, content: { records: [{ id: "recCmTdywUZc3mRYr", createdTime: "2023-01-28T22:24:08.000Z", fields: { Description: "Apple", Qty: 9 } }, { id: "recDg7dLnRsdwfvbc", createdTime: "2023-01-28T22:24:08.000Z", fields: { Description: "Orange", Qty: 6 } }, { id: "recDhHyMIAS1qGu3E", createdTime: "2023-01-28T22:30:56.000Z", fields: { Description: "Pear", Qty: 1 } }, { id: "recIMEr6bOtpS1Kdd", createdTime: "2023-01-28T22:30:55.000Z", fields: { Description: "Banana", Qty: 10 } }] } },
    records = data.content.records.slice();

records.sort((a, b) => a.fields.Description.localeCompare(b.fields.Description));

console.log(records)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading