Sorting .map in React?

Viewed 34

I have this code

const fields = [
    { key: FORM, field: GSN, items: forms, label: 'FORM' },
    { key: STRENGTH, field: GSN, items: strengths, label: 'DOSAGE' },
    { key: QUANTITY, field: QTY, items: quantities, label: 'QUANTITY' }
]

which is being called in with:

{fields.map(({ field, key, items }) => {
    const v = inputs[key]
    const item = items.find(i => i[field] === v || i[key] === v)
    return item ? (
        <div key={key}>
            {item[key]}
        </div>
    ) : null
})}

I am looking to sort the items. The items are only numbers, but no matter where I add sort(), it throws errors. What would be best practice for sorting the output in order from lowest to highest number?

2 Answers
{fields.sort((a,b) => (a.items > b.items) ? 1 : ((b.items > a.items) ? -1 : 0)).map(({ field, key, items }) => {
    const v = inputs[key]
    const item = items.find(i => i[field] === v || i[key] === v)
    return item ? (
        <div key={key}>
            {item[key]}
        </div>
    ) : null
})}

You could do something like this. The idea being to sort your array ahead of time, then map the sorted array instead. You could sort based on the field you require. In this case I used the "key" key with some made up info.

Hope this helps.

const fields = [
  { key: 9, field: "GSN", items: "forms", label: 'FORM' },
  { key: 4, field: "GSN", items: "strengths", label: 'DOSAGE' },
  { key: 51, field: "QTY", items: "quantities", label: 'QUANTITY' }
]

const sorted = fields.sort((a, b) => {
  return a.key - b.key
})

return (
  <div>      
    {sorted.map((item, key) => {
      return (
        <div key={key}>
          {item.key}, {item.field}, {item.items}
        </div>
      )
    })}
  </div>
 );
}
Related