Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort Odds and Evens in a Dart List

Tags:

list

sorting

dart

Cant figure out how to do it.

I'm using sort() with compareTo() to sort a list ascending by one criteria, but i need to resort it with a second criteria, keeping odd numbers in the beggining of the list.

widget.tasks.sort((a,b){
          return a.key.compareTo(b.key);
        });

This code above just sorts one of the attributes of the list. A need to sort a second one of integer numbers.

like image 279
vaugusto Avatar asked Mar 02 '23 11:03

vaugusto


1 Answers

Here is working Example Copy code and run

 List numlist = [1, 2, 3, 4, 5, 6, 7, 9, 10];

  List oddList = [];
  List evenList = [];
  List firstOddThenEven = [];

  for (final i in numlist) {
    if (i.isEven) {
      evenList.add(i);
    } else if (i.isOdd) {
      oddList.add(i);
    }
  }

  firstOddThenEven.addAll(oddList);
  firstOddThenEven.addAll(evenList);
  print(firstOddThenEven);
like image 180
Chanaka Weerasinghe Avatar answered Mar 28 '23 04:03

Chanaka Weerasinghe