Hold array elements with multiple properties - javascript

I currently have this JavaScript array. I have used this sorted list of numbers to generate a list of tournament brackets where a team's seed is taken into account.
The problem is that to carry out my seeding algorithm, I work out the 2 teams in the final, and use their seed to work out the previous matches, which would be using seeds[0] and seeds[1] giving me 1 and 2. But this causes problems when I'm trying to manually enter the name of the team.
Here is the current array:
var seeds = [
1,2,3,4,5,6,7,8
]
I would like to use something where I can refer to seeds[0].id to get their seed number, and when it comes to printing out their name for the tournament brackets I can use seeds[0].name such that:
var seeds = [
{ id : 1, name : "Team 1" },
{ id : 2, name : "Team 2" },
etc
]
What do you think the best way to do this would be? The main problem is that when creating a list of matches to be placed into the brackets which are seeded, I am using the seed number, and then creating a new array of the seeds in the correct seeded order so that I can just print the brackets as newSeeds[0] vs newSeeds[1] & newSeeds[2] vs newSeeds[3] and so on.
Any help appreciated.

I would suggest this way,
Create a class seed which has all the properties of seeds as instance variables.
When creating the seeds array, keep pushing those seed objects into the array instead of any random hashmap.
So when you iterate over the array, you can call methods on each object(seed object) which can do the desired thing for you.

Related

How can i limit array size in type script?

const arrPassword = []
const passarrayLength = 5
function addPassword(passwd) {
if(arrPassword.length === passarrayLength)
{
arrPassword.shift()
}
arrPassword.push(passwd)
console.log(arrPassword.length)
console.log(arrPassword)
}
addPassword('Pass')
addPassword('Pass2')
addPassword('Pass3')
addPassword('Pass4')
addPassword('Pass5')
addPassword('Pass6')
addPassword('Pass7')
addPassword('Pass8')
addPassword('Pass9')
addPassword('Pass10')
I have a few cases where I want to store objects like user password history in an Array of objects to ensure he has not used the password in the last 5 times for example. My question is can I specify an array of objects with a size of 5 and then just push new passwords to array and any object in the array above size set would be discarded ? Or do I have to do this my self where I count the objects in my Array and if it is = max size I pop the oldest one before I push the new object to array ?
Based on the research I did typescript or javascript does not have a fixed array size, I can specify a array of 3 5 objects but will need to assign all 5 and even so the push would make it 6 objects as there is no limit.
So what would be the best approach to handle this ?
I included some basic concept i cam up with
Can I specify an array of objects with a size of 5 and then just push new passwords to array and any object in the array above size set would be discarded?
Nope. Arrays in javascript do not have a maximum size, so there is no "built in" way to do this.
Or do I have to do this my self where I count the objects in my Array and if it is = max size I pop the oldest one before I push the new object to array?
Yep, that's exactly right. It shouldn't be too hard to make a little class that handles this logic.
When i need a functionality and there happens to be no such a functionality, the first thing that i think is "what am i missing?".
In this particular case all you need to do is to take the last passarrayLength many items from your arrPassword array and reassign it to the arrPassword array like;
arrPassword = arrPassword.slice(-passarrayLength);
like
[1,2,3].slice(-5); // <- [1,2,3]
[1,2,3,4,5,6,7,8,9].slice(-5); // <- [5,6,7,8,9]

JavaScript | How can I reference multiple instances of specific data in an array of objects?

SUMMARY: I am creating a small, recreational project where the user enters their drink preferences and the website returns drinks that correspond to the preferences. The drinks are stored in objects within an array.
EXPECTED: I have 6 drinks (objects) within an array named drinks2020[]. Each object within the array follows the same convention - containing a name, type, base, ingredients, and method. For example:
let drinks2020 = [
house_punch = {
"name": "House Punch",
"type": "punch",
"base": "bourbon",
"ingredients": "1oz Bourbon, 1oz Orange Juice, 0.25oz Lemon Juice, 0.50oz Cinnamon-Vanilla, 0.25oz Allspice.",
"method": "Shake and strain into glass mug with orange ice cube."
}
];
I am starting small with the user's preferences, working with the base. If the user inputs 'Bourbon', the app should return all drinks with "base": "bourbon".
PROBLEM: This may be more of a conceptual problem, but I've found that I can't create an if-statement using the "base" value of each object value without explicitly referencing a value in the array. My intention looks something like this:
if (base === 'bourbon') {
console.log(drinks2020[].base);
}
This returns an error as [] is unexpected. Of course, I can call drinks2020[0].base and the app will return bourbon. Yet, I can't call drinks2020[0,1,2,3].base (etc).
CONSIDERATIONS: If I remove the name values, and create an array of objects without object literals, I think I would be able to retrieve the data using drinks2020.base. However I feel it will be easier as I expand the app to have another layer of naming conventions.
QUESTION: What are some resources I can look into about array/object hierarchy, and are there any javaScript methods that could help me with referencing the data of all objects in an array?
EDIT: This is a solution that worked for me:
let spirit = prompt("What spirit do you prefer?");
for (let i = 0; i < drinks2020.length; i++ ) {
if (drinks2020[i].base == spirit) {
returnArr.push(drinks2020[i].name);
let showDrinksAsString = returnArr.join(', ');
document.getElementById('drink_name').innerHTML = showDrinksAsString;
}
}
you can use filter function.
const drinks = drinks2020.filter( drink => drink.base === 'bourbon' );
Refer MDN docs on filter here .

Idempotency in MongoDB nested array, possible?

I am writing a REST api which I want to make idempotent. I am kind of struggling right now with nested arrays and idempotency. I want to update an item in product_notes array in one atomic operation. Is that possible in MongoDB? Or do I have to store arrays as objects instead (see my example at the end of this post)? Is it for example possible to mimic the upsert behaviour but for arrays?
{
username: "test01",
product_notes: [
{ product_id: ObjectID("123"), note: "My comment!" },
{ product_id: ObjectID("124"), note: "My other comment" } ]
}
If I want to update the note for an existing product_node I just use the update command and $set but what if the product_id isn't in the array yet. Then I would like to do an upsert but that (as far as I know) isn't part of the embedded document/array operators.
One way to solve this, and make it idempotent, would be to just add a new collection product_notes to relate between product_id and username.
This feels like violating the purpose of document-based databases.
Another solution:
{
username: "test01",
product_notes: {
"123": { product_id: ObjectID("123"), note: "My comment!" },
"124": { product_id: ObjectID("124"), note: "My other comment" } }
}
Anyone a bit more experienced than me who have anything to share regarding this?
My understanding of your requirement is that you would like to store unique product ids (array) for an user.
You could create an composite unique index on "username" and "username.product_id". So that when the same product id is inserted in the array, you would an exception which you could catch and handle in the code as you wanted the service to be Idempotent.
In terms of adding the new element to an array (i.e. product_notes), I have used Spring data in which you need to get the document by primary key (i.e. top level attribute - example "_id") and then add a new element to an array and update the document.
In terms of updating an attribute in existing array element:-
Again, get the document by primary key (i.e. top level attribute -
example "_id")
Find the correct product id occurrence by iterating the array data
Replace the "[]" with array occurrence
product_notes.[].note

Search for elements that have a particular attribute in array

One element of my mongo collection has the following schema (and represents one poker hand).
{
"players":
[
{"active":true,"seat":1,"stack":1769,"screenName":"schla"},
{"active":true,"seat":3,"stack":2000,"screenName":"galgegla"},
{"active":true,"seat":4,"stack":483,"screenName":"khrier"},
{"active":true,"seat":5,"stack":2813,"screenName":"frrou4535"},
{"active":true,"seat":6,"stack":4002,"screenName":"Guabounai"}
],
"rounds":[],
"gameNum":"1030564654564",
"time":"2013/12/21 21:12:03"
}
I'd like to search for all hands in my collection that have at least one time the player with screenName "galgegla" inside the players array.
Supposing your collection is called 'hands', you can do following:
db.hands.find( { 'players.screenName': 'galgegla' } )
See example under 'Match a Field Without Specifying Array Index' here: http://docs.mongodb.org/manual/tutorial/query-documents/#match-a-field-without-specifying-array-index
Try this:
a.filter(function(arr){
return arr.players.filter(function(player){
return player.screenName == 'galgegla';
}).length;
});
Assuming a is a array of those objects.
It filters the array of objects based on weather or not a filter on the object's players array returns any results.
... But of course I didn't consider mongo's native functionality, so the other answer'd be more effective. (But possibly not as efficient)

Javascript/jQuery Id check to drive numbering function with validation

I need help with a loop... it's probably simple but I'm having difficulty coding it up.
Basically, I need to check existing Ids for their number so I can create a unique id with a different number. They're named like this: id="poly'+i'" in sequence with my function where i is equal to the number of existing elements. Example: Array 1, Array 2, Array 3 corresponding with i=1 for the creation of Array 1, i=2 for Array 2, etc.
Right now i is based on the total number of existing elements, and my "CreateNew" function is driven off x=i+1 (so the example above, the new element will be named Array 4). The problem is that if you delete one of the middle numbers, the "Create" function will duplicate the high number. i.e. Array 1, 2, 3 delete 2, create new-> Array 1, 3, 3.
I need an if() statement to check if the array already exists then a for() loop to cycle through all i's until it validates. Not sure how to code this up.
The code I'm trying to correct is below (note I did not write this originally, I'm simply trying to correct it with my minimal JS skills):
function NewPanel() {
var i = numberOfPanels.toString();
var x = (parseInt(i)+1).toString();
$('#items').append('<div onclick="polygonNameSelected(event)" class="polygonName" id="poly'+i+'"> Array '+ x +' </div>');
$('div[id*=poly]').removeClass('selected');
$('#poly'+i).addClass('selected');
$('#poly'+i).click(function() {
selectedPolygon = i;
$('div[id*=poly]').removeClass('selected');
$(this).addClass('selected');
});
}
THANK YOU! :)
Please clarify "The problem is that if you delete one of the middle numbers, ". What do you mean by delete? Anyway, the simplest solution is to create two arrays. Both arrays will have the same created id's. Whenever an id is created in the first array, an id will be added to the second array. So when it is deleted from first array, check your second array's highest value and then create this id in first array. I hope this did not confuse you.
Well it is hard to tell why you cannot just splice the array down. It seems to me there is a lot of extra logic involved in the tracking of element numbers. In other words, aside from the index being the same, the ids become the same as well as other attributes due to the overlapping 1, 3, 3 (from the example). If this is not the case then my assumption is incorrect.
Based on that assumption, when I encounter a situation where I want to ensure that the index created will always be an appending one, I usually take the same approach as I would with a database primary key. I set up a field:
var primaryKeyAutoInc = 0;
And every time I "create" or add an element to the data store (in this case an array) I copy the current value of the key as it's index and then increment the primaryKeyAutoInc value. This allows for the guaranteed unique indexing which I am assuming you are going for. Moreover, not only will deletes not affect future data creation, the saved key index can be used as an accessor.

Categories