Home > front end >  Sort a list by repeated elements flutter
Sort a list by repeated elements flutter

Time:03-12

I need to sort an array by most duplicated elements like this:

List<String> list = ['x','y','z','x','y','y']

Desired output:

[y,y,y,x,x,z]

CodePudding user response:

I would suggest moving the frequencies calculation outside of the sorting loop.

void main() {
  List<String> list = ['x', 'y', 'z', 'x', 'y', 'y'];
  Map<String, int> numberOf = {
    for (var x in list.toSet()) x: list.where((item) => item == x).length
  };
  print(list..sort((a, b) => numberOf[b]!.compareTo(numberOf[a]!)));
}

Console log

[y, y, y, x, x, z]

CodePudding user response:

You can do it using the sort function. Here is a working sample:

void main() {
  List list = ['x', 'y', 'z', 'x', 'y', 'y'];
  List copyList = List.from(list);
  list.sort((var a, var b) {
    int numberOfA = copyList.where((element) => element == a).length;
    int numberOfB = copyList.where((element) => element == b).length;
    return numberOfB.compareTo(numberOfA);
  });
  print(list);
}

CodePudding user response:

Other example using sort function:

void main() {
  List list = ['x', 'y', 'z', 'x', 'y', 'y'];
  list.sort((a, b) => b.compareTo(a),);
}

more information about compareTo

  • Related