How to not duplicate same item in a list dart? - arrays

I have created a listView and button and when I click the button it adds an item to listView.
The problem is I don't want actually to repeat the same item in the list.
I've tried the .contains method but it didn't work.
I want a good solution please,

There are different ways to achieve this:
1) Iterate the list and check if every element doesn't have the
properties you consider equal:
items = [Item(id: 1), Item(id: 2)];
newItem = Item(id: 2);
if (items.every((item) => item.id != newItem.id)) {
items.add(newItem);
}
2) Use contains() and override == operator (and override hashCode too)
in the object class with the properties you consider equal.
items = [Item(id: 1), Item(id: 2)];
newItem = Item(id: 2);
if (!items.contains(newItem)) {
items.add(newItem);
}
// inside Item class
#override
bool operator ==(other) {
return this.id == other.id;
}
#override
int get hashCode => id.hashCode;
3) Instead of List use Set, where each element can occur only once. Its default implementation is LinkedHashSet that keeps track of the order.

Instead of List, Use Set.
void main() {
Set<String> currencies = {'EUR', 'USD', 'JPY'};
currencies.add('EUR');
currencies.add('USD');
currencies.add('INR');
print(currencies);
}
output: {EUR, USD, JPY, INR} // unique items only
Reference: Set<E> class

Check if the List already contains the element before you add it:
https://api.flutter.dev/flutter/dart-core/List-class.html
if(!List.contains(element) { add }
The contains method checks for equality, not for reference, so it must work as long as you compare a similar element. If your code isn't working, please provide it to us. Thanks.

If your list contains custom objects you may need to override the equality operator in the custom class.
You could also use a Set instead of a List.

Related

Kotlin: How to check if a field in a List of objects is equal to field of another list of objects

basically the title.
If I had to find what I know as a single field,
a.any {
it.name == "user"
}
Now I've a listOf(Groups)
Which contains a unique ID
I want to check
if user.groups.anyItemInThisList.UNIQUEID == otheruser.groups.anyItemInThisList.UNIQUEID
My data looks like this
{
"groups":[
{
"id":4
"group":"Test Group",
"role":"creator",
"member_count":1,
"userType":"local"
}
]
}
To rephrase your question (making sure I understand correctly), you have two Lists of the same kind of item, and you want to determine if there is any value of the id property of an item that appears in both lists.
To do this with simple code, but O(n^2) time, you could use this. It iterates all items from a and for each item it iterates b to see if there are any matches.
val result = a.any { x1 -> b.any { x2 -> x1.id == x2.id} }
To do it in O(n) you can do it with a Set. This creates a set of the names from the first list, and then it only has to iterate the second list once to see if any of the names are in the first set.
val aIds = a.mapTo(HashSet(a.size)) { it.id }
val result = b.any { it.id in aIds }

How can do array map inside methods in vuejs

How can ı equalize my array ıd and my value ıd and access value.name I didn't do it
This is my code:
activity(val) {
var act = this.items.map(function (val) {
if (element.ActivityID== val) {
return element.ActivityName
}
return act
});
Perhaps this?
activity (val) {
const activity = this.items.find(item => item.ActivityID === val)
return activity && activity.ActivityName
}
This just finds the item with the corresponding ActivityID and then returns its ActivityName.
Your original code contained several possible mistakes:
Two different things called val.
element doesn't appear to be defined.
The return act was inside the map callback. The activity method itself wasn't returning anything.
Not really clear why you were using map to find a single item. map is used to create a new array with the same length as the original array with each item in the new array determined by the equivalent item in the original array. It 'maps' the items of the input array to the items in the output array.

How to check if each and every element has an ID?

We just want to make sure that in the Web codes implemented by Dev team, every element has an ID property value.
How can I check? Thanks!
Test this xpath in your browser: //*[string(#id)] This will not only give you elements which have an id, but also whose id's have some value. It might be possible that the devs forgot to enter the id. Then, use this //* to get all the elements. If you want elements that have an id (blank or filled), then use this //*[#id]
(Assuming you're using Java) there is a method WebElement#getAttribute() where you can get any attribute's value of the element..
We just want to make sure that in the Web codes implemented by Dev team, every element has an ID property value. How can I check?
You need to find all elements first then inside loop you can determine whether every element has attribute ID or not using getAttribute("id") as below :-
public boolean isAllElementsHasId()
{
boolean isAllElementsHasId = true;
List<WebElement> allPageElements = driver.findElements(By.cssSelector("*"));
for(WebElement el : allPageElements)
{
if(el.getAttribute("id") == null)
{
isAllElementsHasId = false;
break;
}
}
return isAllElementsHasId
}
Usage :
if(isAllElementsHasId() == true)
{
System.out.println("All elements in the page has an attribute ID");
}

Move reference between lists in redux store

In my store I have multiple lists of ids which reference to normalized entities.
It looks something like this:
{
list1: [ 1 ],
list2: [],
//other lists
entities: {
1:{data},
...
}
}
Users can edit items and can select in which list the item should be. I can't find an elegant way to move the item from one list to another if the user changed the list while editing.
To move an item I have to remove the item-id from the old list and add it to the new one.
How should I remove the Id from the old list after having written it into the new one? Looking into every list for the Id and if found removing it seems a bit wrong to me.
EDIT:
To explain my use case further:
There can be n lists, which are dates, for example "08-17-2016" and the items in it are events. A user can change the date of an event and so the event needs to move from one date to the other.
I would simply use Array.prototype.filter and check with Array.prototype.indexOf in which list this Id is present:
function moveOrAdd(idToMove, list) {
if (list.indexOf(idToMove) > -1) {
// idToMove was in list so remove
return list.filter(id => id !== idToMove);
} else {
// idToMove wasn't in list so add it
return [...list, idToMove];
}
}
// your store then, assuming an array of id to move or delete
[1, 2, 3 ... 2000].forEach(
index => {
{
list1: [...moveOrAdd(index, list1)],
list2: [...moveOrAdd(index, list2)],
/// etc...
}
}
);

WPF list<t> sort

my first post here.
i have a list"<"frameworkelement> that i'm populating with a select process. each frameworkelement has a uid that holds its ZOrder.
i need to sort these by the ZOrder from lowest to highest. i can get this using a listbox and adding the Uid's like this:
//Add Object Uid's
ListBox lstTempOrder = new ListBox();
foreach(FrameworkElement feObject in MainWindow.Data.SelectedObjects)
{
lstTempOrder.Items.Add(feObject.Uid);
}
//Reorder from 0 to above of the ZIndexes
lstTempOrder.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("", System.ComponentModel.ListSortDirection.Ascending));
but i need to do this with a List"<"FrameWorkElement> and Sort.
Here is the code where i populate the List"<"T> (SelectedObjects and CopyObjectsCollections are List"<"FrameWorkElement>" lists.
foreach(FrameworkElement feObject in MainWindow.Data.SelectedObjects)
{
MainWindow.Data.CopyObjectsCollection.Add(feObject);
}
i've looked at CollectionViewSource and IComparer but i can't really make any sense of it.
I might have miss-read your question, but if you just want to sort your List<T>, then why don't you just use the LinQ OrderBy method?
MainWindow.Data.CopyObjectsCollection =
MainWindow.Data.CopyObjectsCollection.OrderBy(f => f.Uid).ToList();
If that sorts it the wrong way round for your requirements, then you can use this:
MainWindow.Data.CopyObjectsCollection =
MainWindow.Data.CopyObjectsCollection.OrderByDescending(f => f.Uid).ToList();
UPDATE >>>
OrderBy is a LinQ extension method. Add using System.Linq; at the top of your class to use it. f relates to an instance of your FrameworkElement object. The above lambda expression basically means 'sort using the Uid property values'.
UPDATE 2 >>>
The OrderBy method does not alter the original collection... that is why my example sets the collection to the result of the OrderBy method. See this basic example:
List<FrameworkElement> elements = new List<FrameworkElement>();
elements.Add(new FrameworkElement() { Uid = "Object1003-1" });
elements.Add(new FrameworkElement() { Uid = "Object1002-2" });
elements.Add(new FrameworkElement() { Uid = "Object1002-1" });
elements.Add(new FrameworkElement() { Uid = "Object1001-1" });
elements.Add(new FrameworkElement() { Uid = "Object1001-3" });
elements.Add(new FrameworkElement() { Uid = "Object1001-2" });
string result = string.Join(", ", elements.Select(f => f.Uid));
elements = elements.OrderBy(f => f.Uid).ToList();
string orderedResult = string.Join(", ", elements.Select(f => f.Uid));
By comparing the values of result and orderedResult you can see that this orders them perfectly.
UPDATE 3 (and hopefully the LAST one) >>>
Dude, you need to learn about Lambda expressions... take a look at the Lambda Expressions (C# Programming Guide) page at MSDN for more information.
elements = elements.OrderBy(f => f.Uid).ToList();
The f in this Lambda expression is declared in this expression before the '=>'. It is fairly standard to name these parameters with one letter like Exceptions, but we could name it anything:
elements = elements.OrderBy(frameworkElement => frameworkElement.Uid).ToList();

Resources