1

I have 2 arrays of maps where one of them has product ids and quantities; and the other one has product ids, product names and price:

List<Map<String, dynamic>> arr1 = [
    { id: "1", name:"First Item", price: 10 },
    { id: "2", name: "Second Item", price: 12 }
];

List<Map<String, dynamic>> arr2 = [
    { id: "1", quantity: 1 },
    { id: "2", quantity: 3 },
    { id: "3", quantity: 2 }
];

Now I need to get total price of products by combining two arrays by obtaining sum of price * quantites.

I need an array similar to this:

List<Map<String, dynamic>> arr3 =[
   { id: "1", name:"First Item", price: 10, quantity: 1 },
   { id: "2", name: "Second Item", price: 12, quantity: 3 }
];

How can I merge them into one array based on their ids?

1 Answer 1

5

You can merge the array by mapping the first array to the second one.

  final arr3 = arr1.map((product) {
    final quantity = arr2
        .where((quantities) => quantities["id"] == product["id"])
        .map((quantities) => quantities["quantity"] as int)
        .first;
    return product..["quantity"] = quantity;
  });

Full example: https://dartpad.dev/67148d132cb930bc6f1cee6a8a4fcff1

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.