skip to Main Content

I have a List of strings ["pana", "open","peno","alp","palp"]

and i need to sort them by having the letter "p", then alphabetically:

so the result should be ["pana", "palp","peno", "open","alp"]

How can i do this in Flutter

2

Answers


  1. Try something like this

    List<String> words = ["pana", "open", "peno", "alp", "palp"];
    
    words.sort((a, b) {
        // Custom comparison function
        if (a.contains('p') && !b.contains('p')) {
          // If a has 'p' and b does not, a comes first
          return -1;
        } else if (!a.contains('p') && b.contains('p')) {
          // If b has 'p' and a does not, b comes first
          return 1;
        } else {
          // If both have 'p' or both don't have 'p', compare alphabetically
          return a.compareTo(b);
        }
      });
    
    Login or Signup to reply.
  2. This is quite a roundabout way of doing it but:

      var list = [
        "pana",
        "open",
        "peno",
        "alp",
        "palp",
        "kk",
        "can",
        "aaa",
        "111"
        ,"zs",
        "sz",
      ];
      
      var pattern = 'p';
      
      var listStartsWith = list.where((word) => word.startsWith(pattern)).toList()
        ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    
      var listContains = list
          .where((word) => word.contains(pattern) && !word.startsWith(pattern))
          .toList()
        ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
      
        var listContainsNot = list
          .where((word) => !word.contains(pattern) && !word.startsWith(pattern))
          .toList()
        ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    
      var reoderedList = [...listStartsWith, ...listContains, ...listContainsNot];
      
      print(reoderedList);
    

    I will update once I’ve been able to optimise it but we can work off this for now.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search