Dart - find duplicate values on a List - list

how can I find duplicate values on a list,
Let's say I got a List like this:
List<Map<String, dynamic>> users = [
{ "name": 'John', 'age': 18 },
{ "name": 'Jane', 'age': 21 },
{ "name": 'Mary', 'age': 23 },
{ "name": 'Mary', 'age': 27 },
];
How I can iterate the list to know if there are users with the same name?

A simple way would be this:
void main() {
List<Map<String, dynamic>> users = [
{ "name": 'John', 'age': 18 },
{ "name": 'Jane', 'age': 21 },
{ "name": 'Mary', 'age': 23 },
{ "name": 'Mary', 'age': 27 },
];
List names = []; // List();
users.forEach((u){
if (names.contains(u["name"])) print("duplicate ${u["name"]}");
else names.add(u["name"]);
});
}
Result:
duplicate Mary

Probably a cleaner solution with extensions.
By declaring:
extension ListExtensions<E> on List<E> {
List<E> removeAll(Iterable<E> allToRemove) {
if (allToRemove == null) {
return this;
} else {
allToRemove.forEach((element) {
this.remove(element);
});
return this;
}
}
List<E> getDupes() {
List<E> dupes = List.from(this);
dupes.removeAll(this.toSet().toList());
return dupes;
}
}
then you can find your duplicates by calling List.getDupes()
Note that the function removeAll doesn't exist in my current Dart library, in case you're reading this when they implement it somehow.
Also keep in mind the equals() function. In a List<String>, ["Rafa", "rafa"] doesn't contain duplicates.
If you indeed want to achieve this level of refinement, you'd have to apply a distinctBy function:
extension ListExtensions<E> on List<E> {
List<E> removeAll(Iterable<E> allToRemove) {
if (allToRemove == null) {
return this;
} else {
allToRemove.forEach((element) {
this.remove(element);
});
return this;
}
}
List<E> distinctBy(predicate(E selector)) {
HashSet set = HashSet();
List<E> list = [];
toList().forEach((e) {
dynamic key = predicate(e);
if (set.add(key)) {
list.add(e);
}
});
return list;
}
List<E> getDupes({E Function(E) distinctBy}) {
List<E> dupes = List.from(this);
if (distinctBy == null) {
dupes.removeAll(this.toSet().toList());
} else {
dupes.removeAll(this.distinctBy(distinctBy).toSet().toList());
}
return dupes;
}
}

I had a feeling Rafael's answer had code similar to Kotlin so I dug around and saw that these functions are part of the kt_dart library which basically gets the Kotlin standard library and ports it to Dart.
I come from a Kotlin background so I use this package often. If you use it, you can simply make the extension this much shorter:
extension KtListExtensions<T> on KtList<T> {
KtList<T> get duplicates => toMutableList()..removeAll(toSet().toList());
}
just make sure to add kt_dart on your pubspec: kt_dart: ^0.8.0
Example
final list = ['apples', 'oranges', 'bananas', 'apples'].toImmutableList();
final duplicates = list.duplicates; // should be ['apples'] in the form of an ImmutableList<String>

void main() {
List<String> country = [
"Nepal",
"Nepal",
"USA",
"Canada",
"Canada",
"China",
"Russia",
];
List DupCountry = [];
country.forEach((dup){
if(DupCountry.contains(dup)){
print("Duplicate in List= ${dup}");
}
else{
DupCountry.add(dup);
}
});
}

Related

Unit Test to find a keyword in a response array

good day everyone, i am new here,
I have a response data looking like this
[
{
"Outlet": "Outlet1",
"Inventory": 12
},
{
"Outlet": "Outlet2",
"Inventory": 0
},
{
"Outlet": "Outlet3",
"Inventory": 3
},
{
"Outlet": "Outlet4",
"Inventory": 0
}
}
I need to verify if the outlet 1 inventory is exact 12, and every other data EXCEPT outlet1 inventory is 0. do i need to loop the test?
I’ve already tried:
pm.test("Inventory.OnHand Outlet1 == 12", () => {
let Outlet1Result = jsonData.find(a => a.Outlet === "Outlet1")
pm.expect(Outlet1Result.Outlet).to.eql("Outlet1")
pm.expect(Outlet1Result.Inventory).to.eql(12)
});
pm.test("Inventory.OnHand not Outlet1 == 0", () => {
if (jsonData.Outlet !== "Outlet1") {
jsonData.forEach(function() {
let result2 = jsonData.find(a => a.Outlet !== "Outlet1")
pm.expect(result2.Inventory).to.eql(0)
}) ;
}
});
I have tried using this 2 test, the first test worked just fine, but i think the second test is wrong because it’s passed, it should not be passed since outlet 3 inventory is 3, the text expect it to be 0
Other way would be :
pm.test("Validate inventory values", () => {
jsonData.forEach(function (item) {
if (item.Outlet !== "Outlet1") {
pm.expect(item.Inventory,
`Expected inventory value of ${item.Outlet} to be 0`).
to.
eql(0)
} else {
pm.expect(item.Inventory,
`Expected inventory value of ${item.Outlet} to be 12`).
to.
eql(12)
}
})
});
why can't you just compare the object as it is than individual fields ? as you are comparing exact values.
let expected = [
{
"Outlet": "Outlet1",
"Inventory": 12
},
{
"Outlet": "Outlet2",
"Inventory": 0
},
{
"Outlet": "Outlet3",
"Inventory": 3
},
{
"Outlet": "Outlet4",
"Inventory": 0
}
]
pm.expect(JSONdata).to.be.deep.eq(expected1, `Expected ${JSON.stringify(JSONdata,null,2)} to be equal to ${JSON.stringify(expected,null,2)}`)

How to remove Map from list in dart

How can remove Map from list based on key value in map, in dart
void main() {
List<Map> names = [
{"id": 1, "name": "Bob"},
{"id": 2, "name": "Alex"},
];
names.forEach((element) {
element.keys.where((key) => element[key] == 1).forEach((names.remove));
});
print(names);
}
I try the above code but it does not works for me.
Thanks
names.removeWhere((element) => element["id"] == 1);

Using python re regex in MongoDB $filter condition

I have a document like below:
{
_id: 1,
data: [ { zip: 001, city: "abc" }, { zip: 002, city: "xyz" } ]
}
I want to filter data array using python regex. But it doesn't seem to be working.
city = "abc"
regx = re.compile("^%s$" %city, re.IGNORECASE|re.MULTILINE)
for doc in db.testusers.aggregate([ { "$project": { "data": { "$filter": { "input": "$data", "as": "item", "cond": { "$eq": [ "$$item.city", regx ] } } } } } ]):
json.dumps(doc)
It doesn't match anything.
Am I doing it right?
I think $filter does not support regex. See doc.
I cannot test this here but it should work like according to this sample:
city_list = ["cityAbc", "Metroid"]
city_list = [re.compile("^" + str(c_id) + "$", re.IGNORECASE) for c_id in city_list]
pipe = [ { "$match" : { "_id":{"$in" : city_list}}},
{ "$unwind" : "$rp"},
{"$group":{"_id": "$_id", "rp": { "$push": "$rp" }}} , {"$limit":500}]
res = list(db.coll.aggregate(pipeline = pipe,allowDiskUse=True))

mapreduce in couchDB and getting the MAX result after mapreduce

I am a beginner to couchDB.
I have data as below:
one:[{
"name":abc,
"value":1
},
{
"name":efg,
"value":1
},
{
"name":abc,
"value":1
},
I would like to get the count of similar keys and get the maximum.
e.g. in my case "abc" is twice. so the maximum(reduce function) should return
result: {"name":abc,value:2}
Did you try this design document:
{
"_id":"_design/company",
"views":
{
"abc_customers": {
"map": "function(doc) { if (doc.name == 'abc') emit(doc.name,doc.value) }",
"reduce" : "_count"
},
"efg_customers": {
"map": "function(doc) { if (doc.name == 'efg') emit(doc.name,doc.value) }",
"reduce" : "_count"
}
}
}
See this one for a comparison of _count and _sum. Possibly you need _count.
By the above CouchDB design document, you will get count for each doc.name of abc, efg, ... and then you can do a search for max/min of counts.

Writing reduce function in couchbase

This is my first attempt at couchbase. My json doc looks like this:
{
"member_id": "12345",
"devices": [
{
"device_id": "1",
"hashes": [
"h1",
"h2",
"h3",
"h4"
]
},
{
"device_id": "2",
"hashes": [
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"h7"
]
}
]
}
I want to create a view which tells me all member_ids for a given hash.
Something like this:
h1["12345","233","2323"] //233,2323 are other member id
h2["12345"]
The member_id should appear once in the set.
I wrote a map function
function (doc, meta) {
for(i=0;i< doc.devices.length;i++)
{
for(j=0;j< doc.devices[i].hashes.length;j++) {
emit(doc.devices[i].hashes[j],null)
}
}
}
and this returns
h1 "12345"
h1 "12345"
h2 "12345"
h1 "233"
but I'm not able to move forward from here. How should I change my map function to reduce the result?
Map function. Mostly yours, but emits meta.id as a value.
function(doc, meta) {
for(i=0; i< doc.devices.length; i++) {
for(j=0; j< doc.devices[i].hashes.length; j++) {
emit(doc.devices[i].hashes[j], meta.id)
}
}
}
Reduce function. Is just return unique array from values (taken from https://stackoverflow.com/a/13486540/98509)
function(keys, values, rereduce) {
return values.filter(function (e, i, arr) {
return arr.lastIndexOf(e) === i;
});
}