简体   繁体   中英

Sort an array of object fetched from db rendered in a Flatlist React native

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM