[Solved] How to get a list of highest values from another list in flutter

Question

Asked by Faris S on December 14, 2021 (source).

I have a list of players consist of 5 objects..

"data": [
    {
      "id": 74,
      "name": "name 1",
      "type": "defender",
      "value": 10
    },
    {
      "id": 7422,
      "name": "name 2",
      "type": "defender",
      "value": 20
    },
    {
      "id": 2213,
      "name": "Max",
      "type": "defender",
      "value": 30
    },
    {
      "id": 3333,
      "name": "John",
      "type": "defender",
      "value": 40
    },
    {
      "id": 8793,
      "name": "Alex",
      "type": "defender",
      "value": 50
    }
  ]

How can I get a list consist of 3 items of the highest values from data list ?

expected results => [Max , John , Alex]

I need only the top 3 items based on highest value

Answer

Question answered by Jahidul I (source).

First sort data based on value then find out the max value

void main() {
  List<Map<String, dynamic>> data = [
    {"id": 74, "name": "name 1", "type": "defender", "value": 10},
    {"id": 7422, "name": "name 2", "type": "defender", "value": 20},
    {"id": 2213, "name": "Max", "type": "defender", "value": 30},
    {"id": 3333, "name": "John", "type": "defender", "value": 40},
    {"id": 8793, "name": "Alex", "type": "defender", "value": 50}
  ];



// sort the data based on 
  if (data != null && data.isNotEmpty) {
    data.sort((a, b) => a['value'].compareTo(b['value']));
  }
// you can simply do this
  for( int i =data.length-3; i< data.length;i++){
    print(data[i]["name"]);
  }
  

  // truncate the max value from the bottom part
  List<Map<String, dynamic>> data1 = data.sublist(data.length-3, data.length);
  
// show the data whom hold the max value
  data1.reversed.forEach((e){
    print(e["name"]);
  });
}

Output: Alex John Max

N.B: you used reversed if you want to print from high to low after getting sorted value

ARRAYS DART FLUTTER LIST
SHARE: