joisberg
joisberg

Reputation: 187

Count element in list

I have a list item:

var listCodeSensations = [4, 3, 2, 3, 2, 4, 3, 4, 2, 5, 2, 2, 3, 4, 5, 6, 0, 4, 8, 3, 2, 1];

And I have in a costant file this model:

  static final List<SensationItem> sensationList = [
    SensationItem(
        code: 0,
        title: 'Formicolio / Intorpidimento'),
    SensationItem(
        code: 1,
        title: 'Sudorazione intensa'),
    SensationItem(
        code: 2, title: 'Dolore al petto'),
    SensationItem(code: 3, title: 'Nausea'),
    SensationItem(code: 4, title: 'Tremori'),
    SensationItem(
        code: 5,
        title: 'Paura di perdere il controllo',
    SensationItem(
        code: 6,
        title: 'Sbandamento / Vertigini'),
    SensationItem(
        code: 7, title: 'Palpitazioni'),
    SensationItem(
        code: 8,
        title: 'Sensazione di soffocamento'),
  ];
}

Now I should insert this in a chartBar (from listCodeSensations) as in the next example:

var dataLine = [
          addCharts('Formicolio / Intorpidimento', 10), //title of sensations, count
          addCharts('Sudorazione intensa', 20), //title of sensations, count
          addCharts('Dolore al petto', 5), //title of sensations, count
          addCharts('Nausea', 14), //title of sensations, count
          addCharts('Tremori', 18), //title of sensations, count
          addCharts('Paura di perdere il controllo', 23), //title of sensations, count
          addCharts('Sbandamento / Vertigini', 6), //title of sensations, count
          addCharts('Palpitazioni', 1), //title of sensations, count
          addCharts('Sensazione di soffocamento', 12), //title of sensations, count
        ];

Upvotes: 1

Views: 86

Answers (1)

Code Updated

const names = [
  'Formicolio / Intorpidimento',
  'Sudorazione intensa',
  'Dolore al petto',
  'Nausea',
  'Tremori',
  'Paura di perdere il controllo',
  'Sbandamento / Vertigini',
  'Palpitazioni',
  'Sensazione di soffocamento',
];

class SensationItem {
  final int code;
  final String title;

  SensationItem({this.code, this.title});
}

class AnyClass {
  static final sensationList = List<SensationItem>.generate(names.length, (i) => SensationItem(code: i, title: names[i]));
}

class AddCharts {
  final String title;
  final int count;

  AddCharts(this.title, this.count);
}

void main(List<String> args) {
  const data = [4, 3, 2, 3, 2, 4, 3, 4, 2, 5, 2, 2, 3, 4, 5, 6, 0, 4, 8, 3, 2, 1];
  var summary = <int, int>{};
  data.toSet().toList()
    ..sort()
    ..forEach((e) => summary[e] = data.where((i) => i == e).length);

  var dataline = List<AddCharts>.generate(names.length, (i) => AddCharts(names[i], summary[i] ?? 0));
  
  print(summary);
}

Result:

{0: 1, 1: 1, 2: 6, 3: 5, 4: 5, 5: 2, 6: 1, 8: 1}

Upvotes: 1

Related Questions