For example, if I have:
var weapon = [ "sword", "mace", "staff"];
var swordtype = [ "long", "short"];
var stafftype = [ "quarter", "magic"];
and my script randomly selects 'Sword' to display in my HTML p tag from the weapon variable.
How can I say that if my code randomly selects "Sword" from the weapon variable, it will also randomly select a "swordtype" to go with it? Making the output either "long sword" or "short sword"?
You'll need to associate related data. So, your structure could be like this:
// Use objects, not arrays to store key/value pairs
var weapons = {
sword:["long","short", "broad"],
mace: ["standard", "long", "short"],
staff: ["quarter", "magic", "wizard"],
"nuclear missle": ["10 megaton", "20 megaton", "50 kiloton"],
dagger: ["standard", "poison"]
};
// Function for selecting random weapon
function getRandomWeapon(){
// Choose random weapon as an index from the weapons object:
var weaponNum = Math.floor(Math.random() * Object.keys(weapons).length);
// Get the property name that corresponds to that key number:
var weapon = Object.keys(weapons)[weaponNum];
// Choose random weapon type as an index from the random weapon selected above:
var specificWeaponNum = Math.floor(Math.random() * weapons[weapon].length);
// Get the array value associated with that index
var specifcWeapon = weapons[Object.keys(weapons)[weaponNum]][specificWeaponNum];
return specifcWeapon + " " + weapon;
}
document.querySelector("button").addEventListener("click", function(){
document.getElementById("weapon").textContent = getRandomWeapon();
});
<div>You have a: <span id="weapon"></span></div>
<button>Get Weapon</button>
Related
I've got 16 objects with names like: aBoard, bBoard, cBoard and so on,
eg. let aBoard = { currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true };
I have an array of corresponding names, randomly chose one of them and change it so it matches the name of one of the objects.
const BOARDARRAY = ["unitA", "unitB", "unitC", "unitD", "unitE", "unitF", "unitG", "unitH", "unitI", "unitJ", "unitK", "unitL", "unitM", "unitN", "unitO", "unitP"];
let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];
let temp = (currentBoardTile.charAt(currentBoardTile.length -1).toLowerCase());
JSObjectBoardUnit = (temp + "Board");
How to access the object using my JSObjectBoardUnit?
In other words, how to make JS "understand" that I want to treat JSObjectBoardUnit value (string) as a value of the object address?
Eg. Let's day JSObjectBoardUnit = aBoard;
Basically the outcome I want is: aBoard.key1 = JSObjectBoardUnit.key1.
I'd love to use the value stored in JSObjectBoardUnit to access the name of the predefined object aBoard.
I'm not sure to understand well your question but I think this 2 methode could maybe help you.
You can access attribute of a object with a string by using
const obj = {toto: 1};
const name = "toto";
console.log(obj["toto"]); // 1
console.log(obj[name]); // here we use variable and the result is 1
so you could store all yoyr object inside one and do this.
const allBoard = {
"aboard": null, // do not put null use your board
}
console.log(allBoard[(temp + "board")]); // display the temp + board attribute so if temps is equal to a then it will get the aboard
this is what you want, getting object from a string.
But I saw that the aboard also have an id attribute with "unitA"
Instead you could build an array of aboard, bboard ....
and use the Array.find() methode that will return the object that match the condition.
in your case
const myBoardArray = [{ currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true }, ....];
let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];
myBoardArray.find((board) => board.ID === currentBoardTile);
2 options
Put the boards in a list, and iterate over them with a for loop. In the for loop, use an if statement to see which Id matches the board you want.
let boards = [aBoard , bBoard, cBoard];
boards.forEach(board=> {
if (board.ID == currentBoardTile) {
//do something
}
});
Create a dictionary where the key is the board id and the respective object is the value. Use the board id to get the respective value.
var boards = {
"unitA" : boardA,
"unitB" : boardB,
....
};
currentBoardTile = BOARDARRAY[randomizer];
console.log(currentBoardTile + " : " + boards[currentBoardTile]);
I am collecting information from a database, based on a filter and is stored in an array of arrays. Once this information is collected I want to be able to print this data onto a new sheet like this:
___________________________________
|*****|John Buck, Associate, Luxura|
------------------------------------
|*****|Jane Doe, Manager, Eclipse |
------------------------------------
|*****|Jim Bob, Executive, Lokia |
------------------------------------
|*****|Suzzy Sue, Director, RoomX |
___________________________________
The most important part is that each time I run this function the array may be a different size, so I need it to continue through the array until all records have been printed down the sheet. I've tried a few things, but I am only used to using forEach or for loops when there is a condition, where as this one would just print the specified info in every array.
function testArray() {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = activeSpreadsheet.getActiveSheet();
var activeRange = activeSpreadsheet.getActiveRange();
var activeCell = activeSpreadsheet.getActiveCell();
var startCell = activeSheet.getRange(5, 4);
var ratingStartCell = activeSheet.getRange(5, 3);
var newArray = [
["John Buck", "*****", "Associate", "Luxura"][
("Jane Doe", "****", "Manager", "Eclipse")
][("Jim Bob", "***", "Executive", "lokia")][
("Suzzy Sue", "*****", "Director", "RoomX")
],
];
newArray.forEach((r, o) => {
startCell.setValues(
newArray[r][0] +
", " +
newArray[r][2] +
", " +
newArray[r][3] +
", " +
newArray[r][4]
);
});
newArray.forEach((r, o) => {
ratingStartCell.setValues(newArray[r][2]);
});
}
By the way, I modified your array. I'm not sure why it contains "()", you can refer to JavaScript Array to learn more on how to declare and use arrays.
You can refer to this sample code:
function testArray() {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = activeSpreadsheet.getActiveSheet();
Logger.log(activeSheet.getSheetName());
var newArray = [
["John Buck", "*****", "Associate", "Luxura"],
["Jane Doe", "****", "Manager", "Eclipse"],
["Jim Bob", "***", "Executive", "lokia"],
["Suzzy Sue", "*****", "Director", "RoomX"]
];
Logger.log(newArray);
//Create new array that will contain expected row values
var rowValues = [];
newArray.forEach((r,o)=>{
//Push a 2-D array, Col1 will be the rating (****) while Col2 will be the remaining strings
//separated by a comma and space
rowValues.push([r[1], r[0]+", "+r[2]+", "+r[3]]);
});
Logger.log(rowValues);
//Set the values for the selected range, using the size of the 2-d array starting from row 5.
activeSheet.getRange(5,3,rowValues.length,rowValues[0].length).setValues(rowValues);
}
What it does?
After fixing your array, I created a new array rowValues which will contain 2 information:
Rating
Concatenated strings separated by a comma and a space.
Once I have created the desired grouping and output for each row. I now set the values of the selected range based on the rowValues created using Sheet.getRange(row, column, numRows, numColumns) and Range.setValues(values)
I set the start row to 5 and start column to 3 based on your earlier example. Feel free to adjust your start row and column index based on your preference.
OUTPUT:
You could post the newArray to activeSheet in one go using the setValues(values) method.
This is more efficient than writing to the sheet on cell at a time. See Best Practices.
activeSheet.getRange(1, 1, newArray.length, newArray[0].length).setValues(newArray);
The size of the array does not need to be specified. newArray.length is the number of rows and newArray[0].length is the number of columns.
You need to be careful when constructing the array: each row must have the same number of columns. If the number of columns is different, you'll get an error and the setValues() will fail.
My arrays:
var mexicanFood = ["Taco Bell", "Beans", "Taco Time", "Buritos", "Chalupa"];
var asianFood = ["Noodles", "Rice", "Sushi", "Fish", "Chicken"];
var americanFood = ["Hot dogs", "Pizza", "Burgers", "Nachos", "Other"];
Know this is a possibility to grab randomly from array:
var randomIndex = Math.floor(Math.random() * mexicanFood.length);
I want to pull a value from each food category. I don't want all of mexicanFood values to be the result for food options. I want it at random but at least to pull one or two from each category. How can you do that with having it go into radio buttons (maybe 5 radio buttons) and can it be done with Math.random?
Also want it to be in javascript and html if possible
Edit:
I basically want different food categories in arrays. Then have random values pulled from the categories and those values will be put into radio buttons. My overall project that I want to create is a voting poll for restaurants to eat at. So I don't want 5 burger places to come up when I have mexican, asian, american, and other options to randomly pull from.
What I am stuck on is how to randomly pull from each array. I know how to randomly pull from one array list. But when I have mexicanFood, asianFood and americanFood (or even more than those), I am not sure how to randomly pull values from those and have those values populate radio buttons
I'm assuming you want to return an array of random foods, containing at least 1 from each category.
I've created a function called createRandomArray(), which accepts an arraySize. This arraySize refers to the amount of items you wish to have in your final array.
In the function, I'm concatenating all of the food arrays together. I'm then looping through this array to add a random index to a new array.
var mexicanFood = ["Taco Bell", "Beans", "Taco Time", "Buritos", "Chalupa"],
asianFood = ["Noodles", "Rice", "Sushi", "Fish", "Chicken"],
americanFood = ["Hot dogs", "Pizza", "Burgers", "Nachos", "Other"];
function createRandomArray(arraySize) {
var allFoods = mexicanFood.concat(asianFood).concat(americanFood),
randomFoods = [];
if (arraySize <= allFoods.length) {
randomFoods = [
mexicanFood[getRandomArrayIndex(mexicanFood)],
asianFood[getRandomArrayIndex(asianFood)],
americanFood[getRandomArrayIndex(americanFood)]
]; // at at least one from each
// remove the ones that were initially added from each
allFoods.splice(allFoods.indexOf(randomFoods[0]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[1]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[2]), 1);
for (var i = 0; i < arraySize - 3; i++) {
var randomIndex = getRandomArrayIndex(allFoods);
randomFoods.push(allFoods[randomIndex]);
allFoods.splice(randomIndex, 1);
}
return randomFoods;
}
return allFoods; // requesting more items of food than the amount available, so just add them all
}
function getRandomArrayIndex(array) {
return Math.floor(Math.random() * array.length);
}
var randomFoods = createRandomArray(5);
for (var i = 0; i < randomFoods.length; i++) {
document.getElementById('food-form').innerHTML += '<input type="radio" name="food" value="' + randomFoods[i] + '"> ' + randomFoods[i] + '<br>';
}
<form action="" id="food-form"></form>
I'm trying to using this JavaScript code:
var aStopWords = new Array ("a", "the", "blah"...);
(code to make it run, full code can be found here: https://jsfiddle.net/j2kbpdjr/)
// sText is the body of text that the keywords are being extracted from.
// It's being separated into an array of words.
// remove stop words
for (var m = 0; m < aStopWords.length; m++) {
sText = sText.replace(' ' + aStopWords[m] + ' ', ' ');
}
to get the keywords from a body of text. It works quite well, however, the issue I'm having is that it only seems to iterate through and ignore one instance of the words in the array aStopWords.
So if I have the following body of text:
how are you today? Are you well?
And I put var aStopWords = new Array("are","well") then it seems it will ignore the first instance of are, but still show the second are as a keyword. Whereas it will completely remove / ignore well from the keywords.
If anyone can help ignore all instances of the words in aStopWords from the keywords, I'd greatly appreciate it.
You can easily do this like this.
First, it splits the text into keywords. Then, it goes through all the keywords. While going through, it checks if it is a stopword. If so, it will be ignored. If not, the occurrence number of this keyword in the result object will be increased.
Then, the keywords are in a JavaScript object in the following form:
{ "this": 1, "that": 2 }
Objects are not sortable in JavaScript, but Arrays are. So, a remapping to the following structure is necessary:
[
{ "keyword": "this", "counter": 1 },
{ "keyword": "that", "counter": 2 }
]
Then, the array can be sorted by using the counter attribute. With the slice() function, only the top X values can be extracted from the sorted list.
var stopwords = ["about", "all", "alone", "also", "am", "and", "as", "at", "because", "before", "beside", "besides", "between", "but", "by", "etc", "for", "i", "of", "on", "other", "others", "so", "than", "that", "though", "to", "too", "trough", "until"];
var text = document.getElementById("main").innerHTML;
var keywords = text.split(/[\s\.;:"]+/);
var keywordsAndCounter = {};
for(var i=0; i<keywords.length; i++) {
var keyword = keywords[i];
// keyword is not a stopword and not empty
if(stopwords.indexOf(keyword.toLowerCase()) === -1 && keyword !== "") {
if(!keywordsAndCounter[keyword]) {
keywordsAndCounter[keyword] = 0;
}
keywordsAndCounter[keyword]++;
}
}
// remap from { keyword: counter, keyword2: counter2, ... } to [{ "keyword": keyword, "counter": counter }, {...} ] to make it sortable
var result = [];
var nonStopKeywords = Object.keys(keywordsAndCounter);
for(var i=0; i<nonStopKeywords.length; i++) {
var keyword = nonStopKeywords[i];
result.push({ "keyword": keyword, "counter": keywordsAndCounter[keyword] });
}
// sort the values according to the number of the counter
result.sort(function(a, b) {
return b.counter - a.counter;
});
var topFive = result.slice(0, 5);
console.log(topFive);
<div id="main">This is a test to show that it is all about being between others. I am there until 8 pm event though it will be late. Because it is "cold" outside even though it is besides me.</div>
var pdata = [{ Name: "Apples", Price: 1.99 },{ Name: "Bananas", Price: 2.45 }];
$('#add1').click(function () {
var selected = $('#produceList option:selected').index();
I have a variable set to an index and I want to get and display the javascript object by the var selected index
HTML
<div class-'item'></div>
JS
$('#add1').click(function () {
var selected = $('#produceList option:selected').index(),
item = pdata[selected];
$('.item').html(item.Name + ', ' + item.Price);
});
JSFIDDLE
If you have the index, you would just do
pdata[index];
so in your example
$('#add1').click(function () {
var index = $('#produceList option:selected').index();
var selected = pdata[index];
})
assuming the code you give in the question gives the index of the selected item.
The pairings are referenced using a simple array index, so your values are:
pdata[0] ---> {Name="Apples", Price=1.99}
pdata[1] ---> {Name="Bananas", Price=2.45}
To get to the specific attributes of the object, you need to use the name of the attribute, so your values are:
pdata[0].Name ---> "Apples"
pdata[0].Price ---> 1.99
pdata[1].Name ---> "Bananas"
pdata[1].Price ---> 2.45
So, to access the information that you want, you would use pdata[index].Name and pdata[index].Price, once you have retrieved the index.