I have an array of ints called SelectedItems. I have another array that contains objects that’s called AvailableItems and that was parsed from json; these Item objects have the properties {ContainerID, ContainerName, ItemID, ItemName}.
I want to convert SelectedItems from an array of ints to an array of Items where each ItemID is replaced with the Item object that corresponds to the ItemID in AvailableItems. Each ItemID in SelectedItems is unique.
I started with 2 loops: one that loops through each element of SelectedItems but then I find myself looping through AvailableItems each time to find the corresponding ItemID with the object keys I need to copy into SelectedItems.
So basically I built a seemingly very inefficient loop. I was wondering if there was a better way to do it by avoiding a repeated loop inside a loop?
Sample data:
For AvailableItems, you have
{
ContainerID: i,
ContainerName: 'SomeName',
ItemID: j,
ItemName: 'SomeOtherName'
}
with may be 1,000 objects and then SelectedItems is array of ints
[23,43,64,34...]
Thanks.
If you are able to get any arbitrary
AvailableItemwithout looping through the whole array by just addressing it by its ID(if you have an index-based array where IDs are indexes) then you can go through theSelectedItemsand check if it exists inAvailableItems, and if it does then you convert theSelecteIteminto an object and add it to some temporary array for later use.