distinct method

CsvTable distinct({
  1. List<String>? columns,
})

Get distinct rows based on all fields or specific columns.

Keys are type-aware: the int 1 and the string "1" are distinct values, and string content cannot forge a key collision.

Implementation

CsvTable distinct({List<String>? columns}) {
  final seen = <String>{};
  final result = <List<dynamic>>[];

  List<int>? colIndices;
  if (columns != null) {
    colIndices = columns.map((c) {
      final idx = headers.indexOf(c);
      if (idx < 0) throw CsvException('Column "$c" not found');
      return idx;
    }).toList();
  }

  for (final row in rawData) {
    final values = colIndices != null
        ? colIndices.map((i) => i < row.length ? row[i] : null)
        : row;
    if (seen.add(_distinctKey(values))) {
      result.add(List<dynamic>.from(row));
    }
  }

  return CsvTable.internal(List<String>.from(headers), result);
}