Home > Back-end >  Flutter Dart How to combine array from an array with similar id?
Flutter Dart How to combine array from an array with similar id?

Time:01-19

Suppose I have array like this?

const info = [
    {
        productId: "1",
        name: "This is product name 1",
        sellerId: "12",
        price: 30,
    },
    {
        productId: "2",
        name: "This is product name 2",
        sellerId: "12",
        price: 50
    },
    {
        productId: "3",
        name: "This is product name 3",
        sellerId: "13",
        price: 50
    }
]

**This is dynamic array. Array value can be changed.

Now I have to combine this array or filter this array. I have not any idea about how can I write function. But my result will be like this-

const result = [
    {
        sellerId: "12",
        productIds: [ //Combine products by similar sellerId
            {
                name: "This is product name 1",
                productId: "1"
            },
            {
                name: "This is product name 2",
                productId: "2"
            }
        ],
        total: 80 //Total price of this two product
    },
    {
        sellerId: "13",
        productIds: [
            {
                name: "This is product name 3",
                productId: "3"
            }
        ],
        total: 50
    }
]

How can I do that in Dart ?

How can I combine array of simillar id and add data if id already have ?

CodePudding user response:

First get a unique list of sellers and map through list. Something like:

final result = info.map((i) => i['sellerId']).toSet().toList()
  .map((s) => {
    "sellerId": s, 
    "productIds": info.where((i) => i["sellerId"] == s)
      .map((p) => {
        "name": p["name"], 
        "productId": p["productId"]
      }).toList(),
    "total": info.where((i) => i["sellerId"] == s)
      .map((p) => p["price"] as int)
      .reduce((acc, v) => acc   v)
  }).toList();

CodePudding user response:

I have created a working example for you. Call the function _filterData() to filter your data as you want.

final List<Map<String, dynamic>> info = [
    {
      "productId": "1",
      "name": "This is product name 1",
      "sellerId": "12",
      "price": 30,
    },
    {
      "productId": "2",
      "name": "This is product name 2",
      "sellerId": "12",
      "price": 50
    },
    {
      "productId": "3",
      "name": "This is product name 3",
      "sellerId": "13",
      "price": 50
    },
    {
      "productId": "1",
      "name": "This is product name 3",
      "sellerId": "13",
      "price": 50
    },
    {
      "productId": "3",
      "name": "This is product name 3",
      "sellerId": "13",
      "price": 50
    }
  ];

  List<Map<String, dynamic>> _filterData() {
    List<Map<String, dynamic>> _result = [];
    Map<String, List<Map<String, dynamic>>> _idAndProducts = Map();
    for (Map<String, dynamic> item in info) {
      if (!_idAndProducts.containsKey(item['sellerId'])) {
        _idAndProducts[item['sellerId']] = [];
      }
      _idAndProducts[item['sellerId']]!.add(item);
    }
    _idAndProducts.entries.forEach((element) {
      _result.add({
        'sellerId': element.key,
        'productIds': element.value,
        'total': _getSum(element.value),
      });
    });
    return _result;
  }

  num _getSum(List<Map<String, dynamic>> products) {
    num sum = 0;
    for (Map<String, dynamic> item in products) {
      sum  = item['price'];
    }
    return sum;
  }
  • Related