Adding all the values in a map in dart - dart

How to add all the values of a map to have the total of 14000?
Map<String, int> salary = {
"user1": 4000,
"user2": 4000,
"user3": 3000,
"user4": 3000,
};

Firstly, you just care about the values of this map, not care about the keys, so we work on the values by this:
var values = salary.values;
And we can use reduce to combine all the values with sum operator:
var values = salary.values;
var result = values.reduce((sum, element) => sum + element);
print(result);
You can reference some basic of List & Map here:
https://api.dartlang.org/stable/1.10.1/dart-core/List-class.html
https://api.dartlang.org/stable/1.10.1/dart-core/Map-class.html

Related

Insert new pair at index 0 to map. ( Dart )

I'm to loop this map. So I would like to be able to insert a pair into this map. How do I do it?
Map<String, String> fruits = {'Apple': 'Golden', 'Orange': 'Orange'};
fruits.insert(0, {'Grape': 'Green'}); // doesn't work
print(fruits); //{Grape: Green, Apple: Golden, Orange: Orange}
Map entries do not have numeric indices (Unless you're working with Map<int, T> of course), and there is no Map.insert method. Instead, the way to add a pair to a map is to assign a value to a key, like so:
fruits['Grape'] = 'Green';
For some additional info, Map is unordered, meaning there is no index 0 - BUT, if you really must have an ordered set of keys and values, you can use List<MapEntry>:
List<MapEntry<String, String>> fruits = [
MapEntry('Apple', 'Golden'),
MapEntry('Orange', 'Orange')
];
fruits.insert(0, MapEntry('Grape', 'Green'));
print(fruits); // [MapEntry(Grape: Green), MapEntry(Apple: Golden), MapEntry(Orange: Orange)]
Even better though, you might consider using a Fruit class, then having a List<Fruit>:
class Fruit {
final String name;
final String color;
Fruit(this.name, this.color});
}
Then:
List<Fruit> fruits = [
Fruit('Apple', 'Golden'),
Fruit('Orange', 'Orange')
];
fruits.insert(0, Fruit('Grape', 'Green'));
print(fruits);
Since the default implementation of a Map is a LinkedHashMap, which preserves the inserting order, you should be able to use this syntax to insert an element either at the start or at the end of a map.
Map<String, String> fruits = {'Apple': 'Golden', 'Orange': 'Orange'};
fruits = {'Grape': 'Green', ...fruits};
print(fruits); //{Grape: Green, Apple: Golden, Orange: Orange}
Be aware that you are actually creating a new Map rather then inserting the element in the existing one.

convert list of maps to one map in dart?

If I have a list of key/value pairs, how would I convert them to a single map?
eg [{'ore': 'value'}, {'pure':'value'}, {'steel':'value}]. =>
{'ore': 'value',
'pure':'value'
'steel':'value'}
Just build a new map containing all the individual map's entries:
List<Map<Something, Other>> listOfMaps = ...;
var combinedMap = {for (var map in listOfMaps) ...map};
Use the reduce function
var v =[{'ore': 'value'}, {'pure':'value'}, {'steel':'value'}];
var w = v.reduce((a,b){
a.addAll(b);
return a;
});

search in maps dart2 , same as list.indexOf?

I Use this sample for search in Map but not work :|:
var xmenList = ['4','xmen','4xmen','test'];
var xmenObj = {
'first': '4',
'second': 'xmen',
'fifth': '4xmen',
'author': 'test'
};
print(xmenList.indexOf('4xmen')); // 2
print(xmenObj.indexOf('4xmen')); // ?
but I have error TypeError: xmenObj.indexOf$1 is not a function on last code line.
Pelease help me to search in map object simple way same as indexOf.
I found the answer:
print(xmenObj.values.toList().indexOf('4xmen')); // 2
or this:
var ind = xmenObj.values.toList().indexOf('4xmen') ;
print(xmenObj.keys.toList()[ind]); // fifth
Maps are not indexable by integers, so there is no operation corresponding to indexOf. If you see lists as specialized maps where the keys are always consecutive integers, then the corresponding operation should find the key for a given value.
Maps are not built for that, so iterating through all the keys and values is the only way to get that result.
I'd do that as:
K keyForValue<K, V>(Map<K, V> map, V value) {
for (var entry in map.entries) {
if (entry.value == value) return key;
}
return null;
}
The entries getter is introduced in Dart 2. If you don't have that, then using the map.values.toList().indexOf(value) to get the iteration position, and then map.keys.elementAt(thatIndex) to get the corresponding key.
If you really only want the numerical index, then you can skip that last step.
It's not amazingly efficient (you allocate a new list and copy all the values). Another approach is:
int indexOfValue<V>(Map<Object, V> map, V value) {
int i = 0;
for (var mapValue in map.values) {
if (mapValue == value) return i;
i++;
}
return -1;
}
You can search using .where(...) if you want to find all that match or firstWhere if you assume there can only be one or you only want the first
var found = xmenObj.keys.firstWhere(
(k) => xmenObj[k] == '4xmen', orElse: () => null);
print(xmenObj[found]);

Highcharts error 14 in chart from HTML table

I'm using the highcharts data module to build a chart from an html table. In the data configuration of the chart I just have:
data: {
table: table
}
But if I have string values such as "null", "NA", or even comma separators in the HTML table I get highcharts error 14, 'string value passed to chart...'
What I've tried:
Since HC should be able to handle null values I replaced NA will null in the tables. I also tried just leaving the blanks "" blank. But the issue is with the thousand separators. So I added thousandsSep: ',' hoping the chart output would understand that commas are part of the display but that doesn't work.
My next thought was to use a formatter function:
data: {
table: function(){...change strings to float etc}
}
None of my attempts at the latter seem to work as I can't figure out what the data object looks like when accessed from a table. Any advice would be appreciated.
A solution that seems to have fixed the issue was to add a "parsed" function here is the api reference: http://api.highcharts.com/highcharts/data.parsed
I added the following to the data property:
data: {
table: 'datatable',
parsed: function()
{
var chartData = this.columns;
var nData = [];
for(var a in chartData)
{
var tempArray = [];
for(var e in chartData[a])
{
var v = chartData[a][e].replace(/\,/g,"").replace("NA","0");
/\d/g.test(v) == true ? v = parseFloat(v) : v = v;
tempArray.push(v);
}
nData.push(tempArray);
}
this.columns = nData;
//alert(JSON.stringify(nData));
//this.columns = [];
//this.columns.push(nData[0]);
//this.columns.push(nData[1]);
}
},
...etc

How to sort map value?

I have this map:
var temp= {
'A' : 3,
'B' : 1,
'C' : 2
};
How to sort the values of the map (descending). I know, I can use temp.values.toList()..sort().
But I want to sort in context of the keys like this:
var temp= {
'B' : 1,
'C' : 2
'A' : 3,
};
This example uses a custom compare function which makes sort() sort the keys by value. Then the keys and values are inserted into a LinkedHashMap because this kind of map guarantees to preserve the order.
Basically the same as https://stackoverflow.com/a/29629447/217408 but customized to your use case.
import 'dart:collection';
void main() {
var temp= {
'A' : 3,
'B' : 1,
'C' : 2
};
var sortedKeys = temp.keys.toList(growable:false)
..sort((k1, k2) => temp[k1].compareTo(temp[k2]));
LinkedHashMap sortedMap = new LinkedHashMap
.fromIterable(sortedKeys, key: (k) => k, value: (k) => temp[k]);
print(sortedMap);
}
Try it on DartPad
The SplayTreeMap has a named constructor which accepts map and a comparator which is used to sort given map while building new map. Since SplayTreeMap is a descendant of Map you can easily substitute it.
import 'dart:collection';
void main() {
var unsorted = {'A': 3, 'B': 1, 'C': 2};
final sorted = SplayTreeMap.from(
unsorted, (key1, key2) => unsorted[key1].compareTo(unsorted[key2]));
print(sorted);
}
final Map<String, ClassCategory> category;
...
Map<String, ClassCategory> sorted = SplayTreeMap.from(category,
(key1, key2) => category[key1]!.title.compareTo(category[key2]!.title));
for (var item in sorted.entries) {
...
}

Resources