I have a Map <String,List> map1 that looks like that
{First: ['1', '2', '3', '4'], Second: ['A', 'B']}
I want to create another Map<String,Map<String,int>> as a ruslt of values from map1 to be like that
{'1A' : ['String1':10,'String2':20], '1B' : ['String1':10,'String2':20] , '2A' : ['String1':10,'String2':20], '2B' : ['String1':10,'String2':20], '3A' : ['String1':10,'String2':20] , '3C' : ['String1':10,'String2':20]}
I hope you get my point
Similar question Generate all combinations from multiple lists
Reference Source: https://stackoverflow.com/a/17193002/6576315
void main() async{
Map<String,List> rawMapList = {"First": ['1', '2', '3', '4'], "Second": ['A', 'B']};
List<Map<String, int>> mapResult = [{"String1" : 10}, {"String2" : 20}];
List<String> keyList = <String>[];
generatePermutations(rawMapList.values.toList(), keyList, 0, "");
var result = Map.fromEntries(keyList.map((value) => MapEntry(value, mapResult)));
print(result);
}
void generatePermutations(List<List<dynamic>> lists, List<String> result, int depth, String current) {
if (depth == lists.length) {
result.add(current);
return;
}
for (int i = 0; i < lists.elementAt(depth).length; i++) {
generatePermutations(lists, result, depth + 1, current + lists.elementAt(depth).elementAt(i));
}
}
Try first on DartPad, This code block will print
{1A: [{String1: 10}, {String2: 20}], 1B: [{String1: 10}, {String2: 20}], 2A: [{String1: 10}, {String2: 20}], 2B: [{String1: 10}, {String2: 20}], 3A: [{String1: 10}, {String2: 20}], 3B: [{String1: 10}, {String2: 20}], 4A: [{String1: 10}, {String2: 20}], 4B: [{String1: 10}, {String2: 20}]}
Do upvote reference
the solution
Map<String, dynamic> data = {
'First': ['1', '2', '3', '4'],
'Second': ['A', 'B']
};
Map<String, dynamic> ans = {};
calculate() {
for (var i in (data['First'] as List<dynamic>)) {
for (var j in (data['Second'] as List<dynamic>)) {
ans.addAll({
"$i$j": [
{'String1': 10},
{'String2': 20}
],
});
}
}
log("$ans");
}
Related
I'm a self-learning beginner at coding, failing at a self-set task. The aim of the task is ultimately to figure out the syntax...but I spent hours now. So...help pls! Warning: I thoroughly confused myself...so don't expect beauty in my attempt.
I want to use iterate over this map:
const marginsCard = [
{
'ID': 0,
'margins': [
{'marginLeft': 0},
{'marginRight': 5},
{'marginBottom': 0},
{'marginTop': 20},
],
},
{
'ID': 1,
'margins': [
{'marginLeft': 5},
{'marginRight': 0},
{'marginBottom': 0},
{'marginTop': 20,},
],
},
{
'ID': 2,
'margins': [
{'marginLeft': 5},
{'marginRight': 0},
{'marginBottom': 0},
{'marginTop': 20,},
],
},
];
The goals are to
iterate over 'ID'
hand over the values for the margins to a constructor method that
hand back a Card with the specified margins
put those Cards in a list.
The function calling the constructor function in its current state:
buildCardElementList(){
cardElementsList = [
...(marginsCard[int.parse('ID')] as List<Map<String,Object>>).map((cardElement){
return buildCardElement(cardElement['marginLeft'], cardElement['marginRight'], cardElement['marginBottom'], cardElement['marginTop']);
}).toList()];
return cardElementsList;
}
There is so much try and eror in this, I'm sure there are multiple issues. Can someone help me out with clean syntax so I can start to understand what I'm doing again?
Thanks!
EDIT // P.S.: I'm leaving out the receiving/constructing function; it's not the issue.
Enjoy ;)
void main() {
final cards = marginsCard.map(_buildCard).toList();
print(cards);
}
Card _buildCard(Map<String, Object> cardElement) {
return Card(
marginLeft: resolveMargin(cardElement, 'marginLeft'),
marginRight: resolveMargin(cardElement, 'marginRight'),
marginBottom: resolveMargin(cardElement, 'marginBottom'),
marginTop: resolveMargin(cardElement, 'marginTop'),
);
}
num resolveMargin(Map<String, Object> cardElement, String marginName) {
final marginElements = cardElement['margins'] as List<Map<String, Object>>;
return marginElements.firstWhere((marginElement) => marginElement.containsKey(marginName))[marginName] as num;
}
class Card {
final num marginLeft, marginRight, marginBottom, marginTop;
Card({required this.marginLeft, required this.marginRight, required this.marginBottom, required this.marginTop});
#override
String toString() => "marginLeft: $marginLeft; marginRight: $marginRight; marginBottom: $marginBottom; marginTop: $marginTop";
}
const marginsCard = [
{
'ID': 0,
'margins': [
{'marginLeft': 0},
{'marginRight': 5},
{'marginBottom': 0},
{'marginTop': 20},
],
},
{
'ID': 1,
'margins': [
{'marginLeft': 5},
{'marginRight': 0},
{'marginBottom': 0},
{'marginTop': 20,},
],
},
{
'ID': 2,
'margins': [
{'marginLeft': 5},
{'marginRight': 0},
{'marginBottom': 0},
{'marginTop': 20,},
],
},
];
I have
Map<String, List<String>> myMap = {'A': ['A','B','C'], '1': ['1','2','3'], '2': ['4','5','6'] };
I would like to convert the numerical values in Lists '1' and '2' from String to type Double.
This is what I want to achieve:
Map<String, List<String>> myMap = {'A': ['A','B','C'], '1': [1.00, 2.00, 3.00], '2': [4.00, 5.00, 6.00] };
void main() {
Map<String, List<dynamic>> myMap = {
'A': ['A', 'B', 'C'],
'1': ['1', '2', '3'],
'2': ['4', '5', '6']
};
myMap.forEach((key, value) {
List<double> list = [];
if (isNumeric(key)) {
myMap[key].forEach((value) {
list.add(double.parse(value));
});
myMap[key] = list;
}
});
print(myMap);
}
//check if string value is numeric
bool isNumeric(String s) {
if (s == null) {
return false;
}
return double.parse(s, (e) => null) != null;
}
OUTPUT :
{A: [A, B, C], 1: [1.0, 2.0, 3.0], 2: [4.0, 5.0, 6.0]}
I'm trying to sort a list by frequency.
List myList = ["a", "b", "c", "d", "e", "f", "d", "d", "e"];
My expected output would be that the list is sorted on frequency & has no duplicated elements.
(myList has 3x "d" and 2x "e").
List output = ["d", "e", "a", "b", "c", "f"];
What's the most efficient way to do it?
Thanks in advance!
Is it also possible to do the same system with a List of Maps/Objects?
List myList2 = [{"letter": a, "info": myInfo}, {"letter": b, "info": myInfo}, ...]
It is not difficult to do that even without using package:collection.
List myList = ['a', 'b', 'c', 'd', 'e', 'f', 'd', 'd', 'e'];
// Put the number of letters in a map where the letters are the keys.
final map = <String, int>{};
for (final letter in myList) {
map[letter] = map.containsKey(letter) ? map[letter] + 1 : 1;
}
// Sort the list of the map keys by the map values.
final output = map.keys.toList(growable: false);
output.sort((k1, k2) => map[k2].compareTo(map[k1]));
print(output); // [d, e, a, b, c, f]
As for the second one, your desired output is unclear, but assuming that the values corresponding to the key letter are String and that you need exactly the same output as that of the first one, you can achieve it in a very similar way.
List myList2 = [
{'letter': 'a', 'info': 'myInfo'},
{'letter': 'b', 'info': 'myInfo'},
{'letter': 'c', 'info': 'myInfo'},
{'letter': 'd', 'info': 'myInfo'},
{'letter': 'e', 'info': 'myInfo'},
{'letter': 'f', 'info': 'myInfo'},
{'letter': 'd', 'info': 'myInfo'},
{'letter': 'd', 'info': 'myInfo'},
{'letter': 'e', 'info': 'myInfo'},
];
final map2 = <String, int>{};
for (final m in myList2) {
final letter = m['letter'];
map2[letter] = map2.containsKey(letter) ? map2[letter] + 1 : 1;
}
final output2 = map2.keys.toList(growable: false);
output2.sort((k1, k2) => map2[k2].compareTo(map2[k1]));
print(output2); // [d, e, a, b, c, f]
I have an events class thats like this
MyEvents(id: 5a9c120ab3473,
title: "Event 1",
description: "",
image: "",
isDone false,
classDate: 2019-08-23 00:00:00.000)
I'm getting a list from a database but i cant figure out how to turn it into this format for a calendar package (there could be multiple events on each day)
Map<DateTime, List<Map<String, Object>>> _events2 = {
DateTime(2019, 8, 24): [
{'name': 'Event A', 'isDone': true},
],
DateTime(2019, 8, 24): [
{'name': 'Event A', 'isDone': true},
],
DateTime(2019, 8, 23): [
{'name': 'Event A', 'isDone': true},
],
};
I've tried this, not sure if I'm on the right track or totally lost
events.map((c) {
print(c.title);
item = {
c.classDate: [
{'name': c.title, 'isDone': true},
]
};
mainList.add(item);
}).toList();
You can add a method in your class like this:
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['title'] = this.title;
data['description'] = this.description;
data['image'] = this.image;
data['isDone'] = this.isDone;
data['classDate'] = this.classDate;
return data;
}
Found this solution
turned out to be exactly what i needed
events.map((c) {
print(c.title);
item = {'name': c.title, 'isDone': true, "class_date": c.classDate};
mainList.add(item);
}).toList();
print("collection");
var c = Collection(mainList.toList());
var result = c
.groupBy$1((e) => e["class_date"],
(e) => {"name": e["name"], "isDone": e["isDone"]})
.toDictionary$1((e) => e.key, (e) => e.toList());
I am trying to use underscorejs to groupBy multiple values based on below data.
var obj = [
{
'Name': 'A',
'Status': 'Ticket Closed'
},{
'Name': 'B',
'Status': 'Ticket Open To Close'
},{
'Name': 'A',
'Status': 'Ticket Closed'
},{
'Name': 'B',
'Status': 'Ticket Open'
},{
'Name': 'A',
'Status': 'Ticket Open To Closed'
},{
'Name': 'A',
'Status': 'Ticket Open'
},{
'Name': 'B',
'Status': 'Ticket Open'
}
];
The expected output is
[{
'Name': Closed',
'Count': [2, 0]
},{
'Name': Open',
'Count': [2, 3]
}]
First object counts all closed tickets (Where the status contains the word closed) for A and B simultaneously. Similarly the second object counts for Open tickets. Here is what I tried
var arr = _.groupBy(obj, function (row) {
return (row["Status"].indexOf('Open') > 0 ? "Open" : "Closed");
});
var arr1 = _.groupBy(arr["Closed"], 'Name');
var arr2 = _.groupBy(arr["Open"], 'Name');
var cData = [];
cData.push(arr1);
cData.push(arr2);
Unable to get count from same code. Any help?
Ok. So I was able to resolve this. Here's the working example
http://jsfiddle.net/7ETKV/
Here is the solved code:
var jsondata = jsondata.sort(function (a, b) {
return a.Name.localeCompare(b.Name);
});
_.each(jsondata, function (row, idx) {
((row.Status.indexOf('Open') > 0) ? jsondata[idx].bgStatus = 'Open' : jsondata[idx].bgStatus = 'Closed');
});
var cdata = [], xobj = {};
var gd = _.groupBy(jsondata, 'bgStatus');
var cats = _.keys(_.groupBy(jsondata, 'Name'));
for (var p in gd) {
var arr = _.countBy(gd[p], function (row) {
return row.Name;
});
_.each(cats, function (row) {
if (!arr.hasOwnProperty(row)) arr[row] = 0;
});
xobj.Name = p;
xobj.Data = _.values(arr);
cdata.push(xobj);
xobj = {};
}
Hope might help someone. Any updates to the code / optimizations are welcome.