0

I have this array of object that i want to sort when i display them on my screen, sort them by type.here is a look of the array:

Array [
  Object {
    "lien": "get_praticien",
    "name": "tag service  centre 2",
    "type": "Tag",
  },
  Object {
    "lien": "get_praticien",
    "name": "Ambulance",
    "type": "Acte",
  },
  Object {
    "lien": "get_praticien",
    "name": "Réadaptation Fonctionnelle",
    "type": "speciality",
  },
  Object {
    "lien": "get_praticien",
    "name": "Infirmité Motrice",
    "type": "Tag",
  },......

so i want the objects that have a type:"speciality" to be at the top of the flatlist, and the others after on whatever order. i'm using a flatlist :

<FlatList 
                data={this.state.dataSource}
                keyExtractor={item=> { return item.id.toString()}}
                renderItem= {({item})=> <MedItem Med={item}  />} />

i'll appreciate you answers

1 Answer 1

2

use a sort function to sort your data list before rendering. Also you may want to sort them on server side if you have multiple pages of data.

const test = [
  {
    "lien": "get_praticien",
    "name": "tag service  centre 2",
    "type": "Tag",
  },
  {
    "lien": "get_praticien",
    "name": "Ambulance",
    "type": "Acte",
  },
  {
    "lien": "get_praticien",
    "name": "Réadaptation Fonctionnelle",
    "type": "speciality",
  },
  {
    "lien": "get_praticien",
    "name": "Infirmité Motrice",
    "type": "Tag",
  },
  {
    "lien": "get_praticien",
    "name": "Infirmité Motrice",
    "type": "speciality",
  },
  {
    "lien": "get_praticien",
    "name": "Ambulance",
    "type": "Acte",
  },
  {
    "lien": "test",
    "name": "test Motrice",
    "type": "speciality",
  },
]

console.log(test.sort((a,b) =>  a.type === 'speciality' ? -1 : 1))

Sign up to request clarification or add additional context in comments.

2 Comments

thanks alot colin it worked!also can i ask why its better to sort them on server side if i have multiple pages of data?
Think about the fetch more use case. If you have multiple page of data, you may fetch a new page of data when user reaches the end of your flat list and concat to your current data array, and it will sort again, push new data with type speciality to the beginning of your Flatlist. Usually you want to push new data to the end of your Flatlist. So it is better to just use limit, offset query to fetch your data on server side, and then render them directly on client side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.