I have two arrays, $user_roles and $global_roles. I want to make a new array, let's call it $available_roles, where it can be equated as the items in $global_roles less the items in the $user_roles
I have the following code to do it to a normal array. $available_roles = array_unique(array_merge($global_roles, $user_roles), SORT_REGULAR);
This is proving to be problematic due to the fact that Laravel does not use traditional arrays when one executes a query, it uses Eloquent Collections.
What other ideas do you guys have?
This is fairly simple. You can use the Collection's merge method:
$available_roles = $global_roles->merge($user_roles);
Because merge internally uses an associative array (dictionary) that uses the id as key, this should automatically remove duplicates.
Anyways though, you can remove duplicates in a collection using unique:
$uniqueCollection = $collection->unique();
Now that was for merging what you're actually are looking for is the difference between two collections. You can do this in two ways:
$available_roles = $user_roles->diff($global_roles);
or
$available_roles = $global_roles->except($user_roles->modelKeys());
Related
For example, I have this data structure
{
easyFilter:1111,
hardFilter:[
{id:1},
{id:2},
...
]
}
If the query I use is like
For u in collection
Filter u.easyFilter=1111 AND "somevalue" IN FLATTEN(u.hardFilter[*].id)
return u
Will the query run faster if I place easyFilter first since it just string comparison on the first level of a object or it does not matter in arango?
Yes, order of FILTER statements does affect performance of query.
Especially in your case, where
easyFilter is just string comparison,
while hardFilter is constructed from multiple operations
iterating array + getting values of defined key
flattening that array
checking if array contains defined value
What's omitted is the importance of indexes. They are THE one behind truly performat queries. Check Handling Indexes in ArangoDB documentation, especially Which Index to use when.
For improving performance of your example would be definitely helpful to add Hash or Skiplist index easyFilter (depends on type / uniqueness of your data). Both indexes support also arrays, but based on documentation, that applies only to simple arrays containing values, not objects.
So, I've got a word analyzing program in Excel with which I hope to be able to import over 30 million words.
At first,I created a separate object for each of these words so that each word has a...
.value '(string), the actual word itself
.bool1 '(boolean)
.bool2 '(boolean)
.bool3 '(boolean)
.isUsed '(boolean)
.cancel '(boolean)
When I found out I may have 30 million of these objects (all stored in a single collection), I thought that this could be a monster to compile. And so I decided that all my words would be strings, and that I would stick them into an array.
So my array idea is to append each of the 30 million strings by adding 5 spaces (for my 5 bools) at the beginning of each string, with each empty space representing a false bool val. e.g,
If instr(3, arr(n), " ") = 1 then
'my 3rd bool val is false.
Elseif instr(3, arr(n), "*") = 1 then '(I'll insert a '*' to denote true)
'my third bool val is true.
End If
Anyway, what do you guys think? Which way (collection or array) should I go about this (for optimization specifically)?
(I wanted to make this a comment but it became too long)
An answer would depend on how you want to access and process the words, once stored.
There are significant benefits and distinct advantages for 3 candidates:
Arrays are very efficient to populate and retrieve all items at once (ex. range to array and array back to range), but much slower at re-sizing and inserting items in the middle. Each Redim copies the entire memory block to a larger location, and if Preserve is used, all values copied over as well. This may translate to perceived slowness for every operation (in a potential application)
More details (arrays vs collections) here (VB specific but it applies to VBA as well)
Collections are linked lists with hash-tables - quite slow to populate but after that you get instant access to any element in the collection, and just as fast at reordering (sorting) and re-sizing. This can translate into a slow opening file, but all other operations are instant. Other aspects:
Retrieve keys as well as the items associated with those keys
Handle case-sensitive keys
Items can be other collections, arrays, objects
While keys must be unique, they are also optional
An item can be returned in reference to its key, or in reference to its index value
Keys are always strings, and always case insensitive
Items are accessible and retrievable, but its keys are not
Cannot remove all items at once (either one by one, or destroy then recreate the Collection
Enumerating with For...Each...Next, lists all items
More info here and here
Dictionaries: same as collections but with the extra benefit of the .Exists() method which, in some scenarios, makes them much faster than collections. Other aspects:
Keys are mandatory and always unique to that Dictionary
An item can only be returned in reference to its key
The key can take any data type; for string keys, by default a Dictionary is case sensitive
Exists() method to test for the existence of a particular key (and item)
Collections have no similar test; instead, you must attempt to retrieve a value from the Collection, and handle the resulting error if the key is not found
Items AND keys are always accessible and retrievable to the developer
Item property is read/write, so it allows changing the item associated with a particular key
Allows you to remove all items in a single step without destroying the Dictionary itself
Using For...Each...Next dictionaries will enumerate the keys
A Dictionary supports implicit adding of an item using the Item property.
In Collections, items must be added explicitly
More details here
Other links: optimizing loops and optimizing strings (same site)
How can I write a NSPredicate that will check if all the elements in an NSArray are the same? I need this for a more complex predicate that I am using to filter NSTableView.
NSPredicate can't tell you if all the items are the same, but you could use it to filter an array for objects that are not equal to object[0]. This wouldn't be particularly performant since it would have to check the entire contents of the array.
You could instead use - (void)enumerateObjectsWithOptions: then bailing out when you find a different object via *stop = YES.
Consider looking at using NSSet, since that is designed to store a collection of unique objects (albeit unordered).
Without knowing more detail it's impossible to say what is the best solution for you.
I have a scope object that has a list containing null values, I would like to sort this list in both directions but the null values must be always at the end. I can probably do this easily by splitting up the object into 2, one with nulls and one without then stick on the null list at the end. But is there a more efficient way to do this?
example:
[1,null,5,7,2,null]
sorted:
ASD: 1,2,5,7,null,null
DESC: 7,5,2,1,null,null
If you just want to sort the array, JavaScript has method array.sort. This takes a comparer function.
You can implement two of such functions one for ascending sorting and one for descending. Within these two functions you can treat nulls as you wish. See documentation here
If you are using angularjs filter orderby it too takes a comparer function, so a similar approach may work.
many people use extensively arrays in Excel/VBA to store a list of data. However, there is the collection object which in my view is MUCH MUCH more convenient (mainly: don't need to re/define length of the list).
So, I am sincerely asking myself if I am missing something? Why do other people still use arrays to store a list of data? Is it simply a hangover of the past?
Several reasons to use arrays instead of collections (or dictionaries):
you can transfer easily array to range (and vice-versa) with Range("A1:B12") = MyArray
collections can store only unique keys whereas arrays can store any value
collections have to store a couple (key, value) whereas you can store whatever in an array
See Chip Pearson's article about arrays for a better understanding
A better question would rather be why people would use collections over dictionaries (ok, collections are standard VBA whereas you have to import dictionaries)
#CharlesWilliams answer is correct: looping through all the values of an array is faster than iterating a Collection or dictionary: so much so, that I always use the Keys() or Items() method of a dictionary when I need to do that - both methods return a vector array.
A note: I use the Dictionary class far more than I use collections, the Exists() method is just too useful.
There are, or course, drawbacks to collections and dictionaries. One of them is that arrays can be 2- or even 3-Dimensional - a much better data structure for tabulated data. You can store arrays as members of a collection, but there's some downsides to that: one of them is that you might not be getting a reference to the item - unless you use arrItem = MyDictionary(strKey) you will almost certainly get a 'ByVal' copy of the array; that's bad if your data is dynamic, and subject to change by multiple processes. It's also slow: lots of allocation and deallocation.
Worst of all, I don't quite trust VBA to deallocate the memory if I have a collection or dictionary with arrays (or objects!) as members: not on out-of-scope, not by Set objCollection = Nothing, not even by objDictionary.RemoveAll - it's difficult to prove that the problem exists with the limited testing toolkit available in the VBE, but I've seen enough memory leaks in applications that used arrays in dictionaries to know that you need to be cautious. That being said, I never use an array without an Erase command somewhere.
#JMax has explained the other big plus for arrays: you can populate an array in a single 'hit' to the worksheet, and write back your work in a single 'hit.
You can, of course, get the best of both worlds by constructing an Indexed Array class: a 2-dimensional array with associated collection or dictionary objects storing some kind of row identifier as the keys, and the row ordinals as the data items.
Collections that auto-resize are slower (theoretically speaking, different implementations will obviously have their own mileage). If you know you have a set number of entries and you only need to access them in a linear fashion then a traditional array is the correct approach.