Home > Enterprise >  Sorting and Array alphabetically
Sorting and Array alphabetically

Time:01-30

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

{
  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))

CodePudding user response:

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; }

CodePudding user response:

Why sorted = inputArray.items.slice() ? With the structure you posted it should be sorted = inputArray.content.records.slice()

And then

sorted.sort((a, b) => a.fields.Description.localeCompare(b.fields.Description))
  • Related