Riyazat Durrani
Riyazat Durrani

Reputation: 668

sort works for int, but not double

The function works if the avgscore contains int value. But if I change the avgscore array to double value, it doesn't work. What all changes I need to do to make it sort the double value as well?

void main() {
      var ids = ['GEORGE', 'RUSTY', 'RIYAZAT', 'JAMES PAWNED'];
      var avgscore = [10, 13, 3, 40];
    
      final persons = List.generate(ids.length, (i) => Person(ids[i], avgscore[i]));
      print(persons); // [GEORGE = 10, RUSTY = 13, RIYAZAT = 3, JAMES PAWNED = 40]
    
      persons.sort((p1, p2) => p2.avgscore.compareTo(p1.avgscore));
    
      print(persons); // [JAMES PAWNED = 40, RUSTY = 13, GEORGE = 10, RIYAZAT = 3]
    
      // If you need to split the values into two arrays again
      ids = persons.map((p) => p.id).toList();
      avgscore = persons.map((p) => p.avgscore).toList();
    
      print(ids); // [JAMES PAWNED, RUSTY, GEORGE, RIYAZAT]
      print(avgscore); // [40, 13, 10, 3]
    }

The error message is:

 Error: A value of type 'List<num>' can't be assigned to a variable of type 'double'.
 - 'List' is from 'dart:core'.
      double avgscore = [10.8, 13.7, 3.9, 10,7];

This is when I change int value to double.

Upvotes: 0

Views: 63

Answers (2)

Maryna Azeez
Maryna Azeez

Reputation: 69

Note that you are making the values five in avgscore while in the ids you have only four values.

instead of this:

var avgscore = [10.8, 13.7, 3.9, 10,7];  // (these are five values based on your error)

try this:

var avgscore = [10.8, 13.7, 3.9, 10.7]; 

or:

List<num> avgscore = [10.8, 13.7, 3.9, 10.7];

Upvotes: 0

Oleg Plotnikov
Oleg Plotnikov

Reputation: 315

I've tried your example and it works fine. You have a mistake in the example avgscore list, the last value should be 10.7 (instead of 10,7). I added the Person class and used explicit types. It seems that you have num avgscore in the Person class.

class Person{
  String id;
  double avgscore;
  
  Person(this.id, this.avgscore);
}
void main() {
      List<String> ids = ['GEORGE', 'RUSTY', 'RIYAZAT', 'JAMES PAWNED'];
      List<double> avgscore = [10.8, 13.7, 3.9, 10.7];
    
      final persons = List.generate(ids.length, (i) => Person(ids[i], avgscore[i]));
    
      persons.sort((p1, p2) => p2.avgscore.compareTo(p1.avgscore));
    
      // If you need to split the values into two arrays again
      ids = persons.map((p) => p.id).toList();
      avgscore = persons.map((p) => p.avgscore).toList();
    
      print(ids); // [RUSTY, GEORGE, JAMES PAWNED, RIYAZAT]
      print(avgscore); // [13.7, 10.8, 10.7, 3.9]
}

Upvotes: 1

Related Questions