Shuffle 4 arrays with paired objects, then push it - javascript

I have 4 arrays which shuffle themselves, works as expected, so far so good.
let groupAB = shuffleArray(["A", "B",]);
let groupCD = shuffleArray(["C", "D",]);
let groupEF = shuffleArray(["E", "F",]);
let groupHG = shuffleArray(["G", "H",]);
but now i want to shuffle the group arrays and push it to a new existing array.
I tried doing it so:
let availablePositions = [];
let groupAB = shuffleArray(["A", "B",]);
let groupCD = shuffleArray(["C", "D",]);
let groupEF = shuffleArray(["E", "F",]);
let groupHG = shuffleArray(["G", "H",]);
let availableGroups = shuffleArray([...groupAB, ...groupCD, ...groupEF, ...groupHG]);
availablePositions.push(...availableGroups);
Which doesnt work as expected. e.g.: "A" "B" get split up and sometimes end up on the other side of the spectrum. To give some visualisation why this needs to be done; I'm making a map for an rts game. "A" to "H" are each a starting position for a player to begin. But i want pairs of people for a 2v2v2v2 scenario. So A and B need to stick together. I'm very noob to JS and its probably an obvious mistake. The script runs without errors.

You can shuffle by groups and flat the array. For example for:
Nodejs11:
let availableGroups = shuffleArray([groupAB, groupCD, groupEF, groupHG]);
let availablePositions = availableGroups.flat();
For lower versions:
let availableGroups = shuffleArray([groupAB, groupCD, groupEF, groupHG]);
availableGroups.forEach((v) => availablePositions.push(...v));

Related

Iterating thorugh array but always returning last value

I am iterating thorugh an array and trying to get different data for each object in array but I end up with same data, if i have three products in billBodies i end up with three item that have the same value (for example i have 3 candies, 2 coffees, and 4 candy bars result I get is 4 candy, 4 candy, 4 candy).
Hope anyone can help i tried to search similar problems but didn't find it though...
for (let bill of dataOfBillHeader.billBodies) {
console.log(dataOfBillHeader)
console.log(this.productToShowOnView)
this.productToShowOnView.cipher = bill.product.cipher;
this.productToShowOnView.name = bill.product.name;
this.productToShowOnView.measure = bill.product.measure;
this.productToShowOnView.count = bill.product.count;
this.productToShowOnView.price = bill.product.price;
this.productToShowOnView.id = dataOfBillHeader.id;
this.productToShowOnView.count = bill.count;
this.productToShowOnView.quantity = bill.quantity;
this.productToShowOnView.discount = bill.discount;
this.productToShowOnView.discountAmount = bill.discountAmount;
this.productToShowOnView.totalPrice = bill.totalPrice;
console.log("to show on view is " + JSON.stringify(this.productToShowOnView));
const newBasket = this.productsInBasket;
this.productsInBasket.push(this.productToShowOnView);
this.productsInBasket = [...newBasket];
this.cd.detectChanges();
}
Well, you are just pushing the same object (reference) in there over and over, namely this.productToShowOnView. Why are you using this.productToShowOnView? Why not a local constant. And with a little magic you can make it a bit smaller, although I don't understand why you would go from one product data format to another one...:
const newBasket = [...this.productsInBasket];
for (let bill of dataOfBillHeader.billBodies) {
const product = {
// no need to get all those individually
...bill.product,
...bill,
//this is weird, all products have the same id?
id: dataOfBillHeader.id,
};
newBasket.push(product);
}
this.productsInBasket = newBasket;
this.cd.detectChanges();

How can I get the last object in this JSON array?

I'm trying to use player data from a football stats API, but I can't seem to get data for the current season (which can be found in the last object in the array). For some reason I'm only getting data for the third index (code below).
.then(data => {
//BIO
const bio = data['data'][0]
const nameValue = bio['fullname']
const imageValue = bio['image_path']
const teamValue = bio['team']['data']['name']
const countryValue = bio['nationality']
const birthdateValue = bio['birthdate']
const heightValue = bio['height']
const positionValue = bio['position']['data']['name']
//STATS
const stats = bio['stats']['data']['data'.length - 1]
const appearancesValue = stats['appearences']
Here is an image of the JSON data I am trying to access. In this instance I should be getting data from [4] but I'm getting it from [3].
I'm quite inexperienced so I feel like I must be making a silly mistake somewhere! Appreciate any help.
the 'data'.length in the bio['stats']['data']['data'.length - 1] part will evaluate to the length of the "data" string. so it is always 4.
You most likely wanted the length of the array so it should be
bio['stats']['data'][bio['stats']['data'].length - 1]
Or you could extract it beforehand in a variable, for clarity
const dataLength = bio['stats']['data'].length;
const stats = bio['stats']['data'][dataLength - 1];
Also since you are using literals for the object properties you do not need to use the [] notation.
const dataLength = bio.stats.data.length;
const stats = bio.stats.data[dataLength - 1];
and you can do that with the rest of the code as well, to avoid typing all the ['..']
Building up on Henry Walker's answer.
Using the new JavaScript Array.at() method allows you to enter both positive and negative indices.
This code:
const dataLength = bio.stats.data.length;
const stats = bio.stats.data[dataLength - 1];
Would simply translate to:
const stats = bio.stats.data.at(-1);
Giving you the last element in the array.
As data object signifies, it has 5 objects in it, you can this particular object at 3rd place as in an array 1st value is stored at index 0. Try using this code to fetch the last object
var lastObject = bio.stats.data[bio.stats.data.length-1].player_id

Why is my code behaving like I have duplicate keys in a dictionary despite using unique strings? Javascript / Appscript

I am trying to loop through a dictionary of customers and save energy usage data, but for some customers when I try to change the values in their usage dictionary it will also change a completely different customer's value. I have a nested dictionary with customer utility information, the top-level key being a unique internal ID.
I stripped my code down to a single loop, looping through the top-level keys and setting the same month's usage for all customers in the dictionary to be the value of the iterator. After that, as shown in the code sample below, I log the values for three customers. After that, I increment only one of those customer's usage, and log the values again. The console shows that two over the customer's have dictionaries that are tied together somehow, but I can't figure out why or how to solve this. I can't discern any pattern in the keys of the linked customers, either.
Structure of the nested dictionary:
CustDict =
{"N0100000XXXXXX" =
{"name" = "XXXX"},
{"address" = "XXXX"},
{"meter_read_dates" =
{"2021-05-13" =
{"usage" = "XXXX"}
}
}
}
Stripped down code I used to demonstrate what is happening as simply as possible (real ID values):
Logger.log(custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000000419887"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000012580668"]["meter_read_dates"]["2021-05-13"]["usage"])
custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"] =
custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"] + 1
Logger.log(custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000000419887"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000012580668"]["meter_read_dates"]["2021-05-13"]["usage"])
Console Output:
11:54:56 AM Info 346.0
11:54:56 AM Info 346.0
11:54:56 AM Info 322.0
11:54:56 AM Info 347.0
11:54:56 AM Info 347.0
11:54:56 AM Info 322.0
Code used to create the CustDict dictionary:
stmtCR = conn.prepareStatement('SELECT cust_id, utility_account, cycle_id, read_cycle FROM customers')
results = stmtCR.executeQuery()
resultsMetaData = results.getMetaData()
numCols = resultsMetaData.getColumnCount();
results.last();
numRows = results.getRow();
i = 0
results.first()
var custDict = {}
while (i < numRows)
{
custDict[results.getString(1)] = {}
custDict[results.getString(1)]["id"] = results.getString(1)
custDict[results.getString(1)]["utility_account"] = results.getString(2)
custDict[results.getString(1)]["cycle_id"] = results.getString(3)
custDict[results.getString(1)]["read_cycle"] = results.getString(4)
results.next()
i++;
}
for (i = 0; i < Object.keys(custDict).length; i++)
{
tempCust = custDict[Object.keys(custDict)[i]]
tempCycleId = tempCust["cycle_id"]
tempReadCycle = tempCust["read_cycle"]
tempCust["meter_read_dates"] = cycleIdShdDict[tempCycleId][tempReadCycle]
custDict[Object.keys(custDict)[i]] = tempCust
}
cycleIdShdDict is a seperate dictionary that contains a set of dates associated with each cycle_id and read_cycle
I suspect the problem is that Object.keys(custDict) is returning the keys in a different order at different places in the for loop. So you're getting the object from one key, and then assigning it to a different key.
There's no need to assign back to custDict[Object.keys(custDict)[i]] since you're modifying the object in place, not a copy.
But instead of looping through the keys, loop through the values and modify them.
Object.values(custDict).forEach(tempCust => {
let tempCycleId = tempCust["cycle_id"];
let tempReadCycle = tempCust["read_cycle"];
tempCust["meter_read_dates"] = cycleIdShdDict[tempCycleId][tempReadCycle];
});

Data management

There is a dataset:
array_A[1~10], arrayB[1~40], array_C[1-30]
I need to classify those dataset,
the result like below.
classify_array_1: some from array_A, some from array_B, some from array_C
classify_array_2: some from array_A, some from array_B, some from array_C
classify_array_3: some from array_A, some from array_B, some from array_C
classify_array_4: the rest.
So In javascript
One way
I can make use of array to store object with those(with type = A, type = B, type = C, and index in the original array), and push the related item to certain array.
classify_array_1 = [];
classify_array_2 = [];
classify_array_3 = [];
classify_array_4 = [];
however, when I need to visit a value: array_A 7, I need to visit all of those classify_array_[1-4] array to find this item(type=A&& id=7)
Another way
I can just create 3 array to store the original data
array_A[1~10], arrayB[1~40], array_C[1-30]
and then put certain to (but add a item in array_A[4].classify=3 )
classify_array_1 = [];
classify_array_2 = [];
classify_array_3 = [];
classify_array_4 = [];
As I know when I make change in classify_array_[1-4], there will also change in array_[ABC],
and when I need to find A 4, I just get from the array_A, and to look its classify property we know the classify information.
But in this way we need another 3 arrays, Is there a good way?
What the data is very huge?
Any suggestion is appreciated, thanks.

javascript rearrange arrays in permutations for jquery selectors

Not sure of the best title for this question so any revision suggestions welcome...
say i have 1 javascript array that look like this:
group[g1] = [v1,v2,v3]
group[g2] = [a1,a2,a3]
group[g3] = [b1,b2,b3]
and so on... ad infinitum
and i want to rearrange this to get
newgroup[z] = [v1,a1,b1]
newgroup[y] = [v1,a1,b2]
newgroup[x] = [v1,a1,b3]
newgroup[w] = [v1,a2,b1]
newgroup[v] = [v1,a2,b2]
newgroup[u] = [v1,a2,b3]
newgroup[t] = [v1,a3,b1]
newgroup[s] = [v1,a3,b2]
newgroup[r] = [v1,a3,b3]
newgroup[q] = [v2,a1,b1]
newgroup[p] = [v2,a1,b2]
newgroup[o] = [v2,a1,b3]
newgroup[n] = [v2,a2,b1]
newgroup[m] = [v2,a2,b2]
newgroup[h] = [v2,a2,b3]
newgroup[g] = [v2,a3,b1]
newgroup[f] = [v2,a3,b2]
newgroup[d] = [v2,a3,b3]
newgroup[q] = [v3,a1,b1]
newgroup[p] = [v3,a1,b2]
newgroup[o] = [v3,a1,b3]
newgroup[n] = [v3,a2,b1]
newgroup[m] = [v3,a2,b2]
newgroup[h] = [v3,a2,b3]
newgroup[g] = [v3,a3,b1]
newgroup[f] = [v3,a3,b2]
newgroup[d] = [v3,a3,b3]
i.e.. making a list of all the permutations of the different ways of grouping those items
Ideally this would be dynamic so that no matter how many groups there were of elements in each group array.. it would also work.
I could then join in newsgroup and link them all together to make one large selector for jquery.
Please help...its beyond me now!
I realised I was looking for a Cartesian product of my original array.. And found the result here.. Lazy Cartesian product of arrays (arbitrary nested loops)… god I love this site

Categories

Resources