I need to merge 2 lists, but sum each item in these lists. It would be this here:
list1 = [1,3,9,7]
list2 = [1,2,3,4,5]
//what I need: [list1(item1) + list2(item1), list1(item2) + list2(item2)...]
expected_return: = [2,5,12,11,5]
I managed to just combine the lists
Deivid Amarante is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
You can loop the the items and create a new list. you need to make sure the index isnot out of range.
import 'dart:math' as math;
void main() {
final list1 = [1, 3, 9, 7];
final list2 = [1, 2, 3, 4, 5];
final List<int> result = [];
for (int i = 0; i < math.max(list1.length, list2.length); i++) {
final a = list1.elementAtOrNull(i) ?? 0;// if null return 0
final b = list2.elementAtOrNull(i) ?? 0;
result.add(a + b);
}
print(result);
}
0
If you want a more functional approach, you can first create a helper function that adds dummy elements so that the two lists are of equal lengths, use IterableZip
from package:collection
to combine the two lists into a list of pairs, and then call reduce
on each pair:
import 'dart:math';
import 'package:collection/collection.dart';
extension<T> on List<T> {
Iterable<T> padTo(int newLength, T padValue) {
if (newLength <= length) {
return this;
}
return followedBy(List.filled(newLength - length, padValue));
}
}
void main() {
var list1 = [1, 3, 9, 7];
var list2 = [1, 2, 3, 4, 5];
var maxLength = max(list1.length, list2.length);
var sums = IterableZip(
[
list1.padTo(maxLength, 0),
list2.padTo(maxLength, 0),
],
).map((list) => list.reduce((a, b) => a + b)).toList();
print(sums); // Prints: [2, 5, 12, 11, 5]
}
To sum corresponding elements from two lists in Flutter, you can use List.generate() along with max() to handle lists of different lengths. Here’s the code snippet:
import 'dart:math';
void _sumTwoList() {
final _list1 = <int>[1, 3, 9, 7];
final _list2 = <int>[1, 2, 3, 4, 5,];
final _resultList = List<int>.generate(
max(_list1.length, _list2.length),
(index) => (index < _list1.length ? _list1[index] : 0) +
(index < _list2.length ? _list2[index] : 0),
);
debugPrint('$_resultList'); // Output: [2, 5, 12, 11, 5]
}