'Flutter categories list base on another list of data

I have two lists and need to get the category of each word and display it as a group. my first list is where data is coming from.

final WordsList = [
  {
    'category': 'category-1',
    'words': ['Happy', 'Excited', 'Playful', 'Content', 'Grateful', 'Inspired']
  },
  {
    'category': 'category-2',
    'words': ['Confused', 'Doubtful','Confused']
  },
  {
    'category': 'category-3',
    'words': ['Scared','Horrified']
  },

Then the second list is from the user selection

List userSelection = [Happy, Confused, Doubtful, Scared, Horrified];

What i want to achieve is below.

Category-1 Category-2 Category-3
Happy Confused Scared
Doubtful Horrified

Here is my code so far what I did was iterate the userSelection list and search the words from the word list and was able to retrieve the list but cannot figure out how to display it properly.

void getCategory() {
    var wordsDisplay = [];
    for (var i = 0; i < userSelection.length; i++) {
      wordsDisplay.add(WordsList
          .where((element) => (element["words"].contains(userSelection[i]))));
    }
  }


Solution 1:[1]

Try this out:

void main() {
  List<Map<String, dynamic>> wordsList = [
    {
      'category': 'category-1',
      'words': [
        'Happy',
        'Excited',
        'Playful',
        'Content',
        'Grateful',
        'Inspired'
      ]
    },
    {
      'category': 'category-2',
      'words': ['Confused', 'Doubtful', 'Confused']
    },
    {
      'category': 'category-3',
      'words': ['Scared', 'Horrified']
    },
  ];

  // using a set to eliminate duplicates like 'Confused' in category-2
  Set<String> userSelection = {
    'Happy',
    'Confused',
    'Doubtful',
    'Scared',
    'Horrified',
  };

  List<Map<String, dynamic>> wordsDisplay = [
    for (final category in wordsList)
      {
        // copy category into a new map
        ...category,
        // overwrite the 'words' key/value pair
        // the items we want are the set intersection of the userSelection
        // and the original words list.
        'words': userSelection.intersection({...?category['words']}),
      },
  ];

  print(wordsDisplay);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mmcdon20