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
Related
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();
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];
});
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));
I am trying to make a game for my two girls. It randomly selects an adjective and a noun, then displays the words for them to act out.
I can get the random words to print to the console, but now I need them to appear in the html.
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
var randomAdj = (["happy", "sad", "bouncy", "silly"].sample());
var randNoun = (["monkey", "butterfly", "puppy"].sample());
document.getElementById(#adj).textContent = randomAdj;
document.getElementById(#noun).textContent = randomNoun;
The last two lines aren't working for me (#adj and #noun are span ids used in the html).
I am only a couple of weeks into learning, so I might be missing something super obvious here.
The random part should work (keep in mind that modifying the prototypes is not a good practice, tho), but you have two syntax errors:
document.getElementById(#adj).textContent = randomAdj;
document.getElementById(#noun).textContent = randomNoun;
Pass "adj" and "noun" as strings:
document.getElementById("adj").textContent = randomAdj;
document.getElementById("noun").textContent = randomNoun;
You don't need the # snippet in the getElementById call.
Also note that you you are using randomNoun but you declared randNoun. Here is the working code and example:
function randomItem(arr){
return arr[Math.floor(Math.random()*arr.length)];
}
var randomAdj = randomItem(["happy", "sad", "bouncy", "silly"]);
var randomNoun = randomItem(["monkey", "butterfly", "puppy"]);
document.getElementById("adj").textContent = randomAdj;
document.getElementById("noun").textContent = randomNoun;
<span id="adj"></span>
<span id="noun"></span>
worng
document.getElementById(#adj).textContent = randomAdj;
document.getElementById(#noun).textContent = randomNoun;
use
document.getElementById("adj").innerHTML = randomAdj;
document.getElementById("noun").innerHTML = randomNoun;
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.