skip to Main Content

I have a list of objects and I want to remove duplicates and also add the number of removed items to the remaining item in the list.

var data = [
  {
    name: "book",
    qty: 1
  },
  {
    name: "book"
    qty: 1
  },
  {
    name: "book",
    qty: 1
  },
  {
    name: "pen",
    qty: 1
  },
  {
    name: "pen",
    qty: 1
  },
 
];

The result should be something like this

[{name: "book", qty: 3},{name: "pen",qty: 2}],

2

Answers


  1. You can do this by using the collection library
    Import the collection library by typing

    import 'package:collection/collection.dart';

    and then use the groupby function to group the items together, Here’s an example code

    var consolidatedData = groupBy(data, (obj) => obj['name'])
          .values
          .map((group) => {
                'name': group.first['name'],
                'qty': group.length,
              })
          .toList();
    

    I hope this helps

    Login or Signup to reply.
  2. Below link may help you. It does have solution to remove duplicate records.

    https://www.fluttercampus.com/guide/175/how-to-unique-list-of-objects-by-property-value-in-dart-flutter/

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