首页 > 解决方案 > 对 2 个依赖飞镖数组进行排序

问题描述

我有 2 个数组

ids=[GEORGE, RUSTY, RIYAZAT, JAMES PAWNED];
avgscore=[10, 13, 3, 40];

我希望结果数组按分数降序排序,并且两个数组都应该相应地排序,结果应该是这样的

ids should be sorted as [40, 13, 10, 3];
avgscore should be sorted as [JAMES PAWNED, RUSTY, GEORGE, RIYAZAT];

标签: flutterdart

解决方案


您应该创建一个将您的两个数据绑定在一起的类。然后很容易根据avgscore值进行排序:

class Person {
  final String id;
  final int avgscore;
  Person(this.id, this.avgscore);

  @override
  String toString() => '$id = $avgscore';
}

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]
}

推荐阅读