skip to Main Content

I’d like to eliminate duplicates based on the properties "name" and "price" of each element and filter the list accordingly.

List<Connector> connectorList = [
  Model(name : "Type A", price : 2.30, value : "Value 1"),
  Model(name : "Type B", price : 2.30, value : "Value 2"),
  Model(name : "Type C", price : 2.30, value : "Value 3"),
  Model(name : "Type A", price : 2.30, value : "Value 4"),
  Model(name : "Type B", price : 3.30, value : "Value 5"),
  Model(name : "Type B", price : 2.30, value : "Value 6"),
]

Output:

List<Connector> filteredConnectorList = [
  Model(name : "Type A", price : 2.30, value : "Value 1"),
  Model(name : "Type B", price : 2.30, value : "Value 2"),
  Model(name : "Type B", price : 3.30, value : "Value 5"),
  Model(name : "Type C", price : 2.30, value : "Value 3"),
]

2

Answers


  1. First of all use equatable package to override the == operator:

    import 'package:equatable/equatable.dart';
    
    class Connector with EquatableMixin {
      final String name;
      final double price;
      final String value;
    
      Connector({
        required this.name,
        required this.price,
        required this.value,
      });
    
      @override
      List<Object?> get props => [name, price];
    }
    

    Then you can easily use Set data structure to achieve your result:

    List<Connector> filteredConnectorList = connectorList.toSet().toList();
    
    Login or Signup to reply.
  2. With the help of the collection package you could do this

    List<Connector> output = groupBy(connectorList, (e) => (e.name, e.price)).values.map((e) => e.first).toList();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search