I am trying compare two arrays. One array is an array of Person objects, each of which has an email property that is a String email address. The other array is an EmailAddress object which has a descriptive word like "work" or "personal" and the actual String email address.
Basically both objects have a String property for email address. I want to compare these arrays of objects to see if one of the objects from each array has the same email address. Right now I am using nested for loops as shown below but that is taking too long.
for person in self.allPeople! {
for e in EmailAddresses! {
if e.value == person.email {
return true
}
}
}
I thought about using set intersection but that looked like it would only work for comparing the same objects and not object's properties. Thanks.
You can still use Set functionality by first creating a set of all the emails. map helps turn one collection into another, in this case changing your collection of allPeople into a collection of those people's emails. This will be faster because now EmailAddresses is iterated once, instead of once per person.
let personEmails = Set(self.allPeople!.map { $0.email })
let matchingEmails = EmailAddresses!.map { $0.value }
return !personEmails.isDisjoint(with: matchingEmails)
Related
I have a mongoose object which contains an array of ObjectIds, being used for population from another table. I want to be able to dedupe these. eg I have
[ '61e34f3293d9361bbb5883c7' ,'61e34f3293d9361bbb5883c7', '61e34f3293d9361bbb5883c7' ]
When i print and iterate through these they look like strings.
But they also have an _id property, so I think they're somehow "populated" or at least contain references to the child table.
What's the best way to do this? I tried:
const uniqueTokens = _.uniqBy(tokens, '_id') which doesn't seem to work as _id is some kind of Object.
converting to a string will allow me to dedupe:
const tokens = this.tokens || []
let newTokens: string[] = []
for (let t of tokens) {
const text = t.toString()
// clog.info('t', t, t._id, typeof t._id)
if (!newTokens.includes(text)) {
newTokens.push(text)
}
}
but then these aren't real Objects I can assign back to the original parent object.
// this.tokens = newTokens
await this.save()
I could maybe go through and re-find the objects, but that seems to be digging deeper into the hole!
Seems there must be a better way to handle these type of types...
related searches
How to compare mongoDB ObjectIds & remove duplicates in an array of documents using node.js?
I also tried using lean() on the tokens array to try and convert it back to a simple list of references, in case somehow the 'population' could be undone to help.
I'm down to creating a unique signature field for the referenced items and de-duping based on that.
I create one entities with a few fruits (apple, banana, orange, avocado)
When my user say any intent that I need to check if have one #Fruits work fine, but if my user say 2 or more fruits I need to save all in one array. how can I does this using slots? because in my test he save only the last (if I print $myFruits)
tks
When the user types two values or more, and this values was inside one entity, the values will be save inside array, and you can access the entity. For example...
You can see in my example, if I types two flavor's, will appear in my console the two values in one array...
Dialog:
Console:
So, if you want all values from the entity #fruits. you can use this method for saves inside one context variable (E.g: $fruits):
<? entities['fruits'][0].value + entities['fruits'][1].value ?> //if types two fruits
And for this to be shown in your dialog, you can use this method:
{
"output": {
"text": "This is the array: <? $fruits.join(', ') ?>"
}
}
The return will be:
This is the array: calabresa, marguerita,
If you want to access all values from your entity with code, you need to access the return from the calling message (for access entities, intents, context variables, etc), and use the following code:
var arrayEntitie = response.entities
for (var i=0; i < arrayEntitie.length; i++) {
if (arrayEntitie[i].name === 'calabreza') { //make your condition
//do something
}
}
Official documentation for accessing methods here.
You can see this Github repository by IBM Developer using context variables here.
Simple way to do is by using #EntityName.values . It will store all the values of given entity in context in form of array.
I am trying to make a Meteor app to let users push a value to the database. It works ok, but there a small issue. As soon a certain user has pushed his information, i don't want to let the same user create another entry. Or this must be blocked, or the value the user is pushing must be overwritten for the value he is posting the second time. Now I get multiple entry's of the same user.
Here is my code. Hope you can help me here. Thanks in advance.
Estimations.update(userstory._id, {
$addToSet: {
estimations: [
{name: Meteor.user().username, estimation: this.value}
]
}
});
From the mongo docs
The $addToSet operator adds a value to an array unless the value is
already present, in which case $addToSet does nothing to that array.
Since your array elements are objects the value is the entire object, not just the username key. This means a single user can create multiple name, estimation pairs as long as the estimation value is different.
What you can do is remove any value for the user first, then reinsert:
var username = Meteor.user().username;
Estimations.update({ userstory._id },
{ $pull: { estimations: { name: username }}}); // if it doesn't exist this will no-op
Estimations.update({userstory._id },
{ $push: { estimations: { name: username, estimation: this.value }}});
By way of commentary, you've got a collection called Estimations that contains an array called estimations that contains objects with keys estimation. This might confuse future developers on the project ;) Also if your Estimations collection is 1:1 with UserStorys then perhaps the array could just be a key inside the UserStory document?
I´m developing a grails app, and I already have a domain class "ExtendedUser" wich has info about users like: "name", "bio", "birthDate". Now I´m planning to do statistics about user´s age so I have created another controller "StatisticsController" and the idea is to store all the birthDates in a local array so I can manage multiple calculations with it
class StatisticsController {
// #Secured(["ROLE_COMPANY"])
def teststat(){
def user = ExtendedUser.findAll() //A list with all of the users
def emptyList = [] //AN empty list to store all the birthdates
def k = 0
while (k<=user.size()){
emptyList.add(user[k].birthDate) //Add a new birthdate to the emptyList (The Error)
k++
}
[age: user]
}
}
When I test, it shows me this error message: Cannot get property 'birthDate' on null object
So my question is how is the best way to store all the birthdates in an single array or list, so I can make calculations with it. Thank you
I prefer to .each() in groovy as much as possible. Read about groovy looping here.
For this try something like:
user.each() {
emptylist.push(it.birthdate) //'it' is the name of the default iterator created by the .each()
}
I don't have a grails environment set up on this computer so that is right off the top of my head without being tested but give it a shot.
I would use this approach:
def birthDates = ExtendedUser.findAll().collect { it.birthDate }
The collect method transforms each element of the collection and returns the transformed collection. In this case, users are being transformed into their birth dates.
Can you try:
List dates = ExtendedUser.findAll().birthDate
I'm trying to build a simple Mobile Service on Azure and I'm having some problems while inserting my information. Right now, I've got two classes in my model, User and Car. A User has an AccountID, a Name (all these Strings) and an Array of Car. A Car has a Plate, a Color and a Model (all these Strings).
I'm serializing the User object correctly to JSON and when I try to do request.execute() it throws an error that says "The value of property 'cars' is of type object which is not supported". I know that only string, number, bool and date are suppported.
What I'd like to do, is to have two separate tables, one for users and another one for cars, and somehow establish a relationship between them. This is the script I've written so far
function insert(item, user, request) {
if(item.accountID !== user.userId){
request.respond(statusCodes.UNAUTHORIZED,
"Unauthorized user");
} else {
if(item.cars.length){
var tableCars = tables.getTable('cars');
populateTable(tableCars, request, item.cars);
}
request.execute();
}
}
function populateTable(table, request, array){
var index = 0;
var insertNext = function(){
if(index < array.length){
var toInsert = array[index];
table.insert(toInsert, {
success: function(){
index++;
insertNext();
}
});
}
};
insertNext();
}
At this point I've got several problems. If I leave it this way, it crashes because items.cars is an Array of Car (an object for JS) but I do want to have here some kind of id to find cars that belong to this User in its table. Maybe I should add some kind to 'owner' to Car, but I'm not sure, my knowledge of databases is somehow poor.
What should I do?
Azure table storage does not support relational tables. Furthermore, ATS does not support storing of strongly typed child objects as a part of parent entities. ATS is a key-value entity-based table storage. It only supports basic data types like string, date, double, boolean, etc.
If you want to store complex objects in ATS (complex, meaning objects that contain other objects), it is suggested that you should serialize the child objects as strings rather then objects, when storing the data and de-serialize the strings back into objects during retrieval.
Alternatively, you can get very fancy with your Row/PartitionKeys and store Parent object and child objects as different entities within the same PartitionKey - and when reading the values back, reconstruct the hierarchy.