This question already has answers here:
Getting a random value from a JavaScript array
(28 answers)
Closed 24 days ago.
I am doing a project in JS and Node.js and I need to extract a random element from my array and then display it.
// enemies.js
const enemies = [
"Wizard Monster",
"Ice Golem",
"Electro Dragon",
"Fire Giant",
"Rahzar Mutant",
]
export default enemies
// fight.js
import enemies from "../utils/enemies.js"
// Code here
Any ideas ?
Thanks in advance.
Something like below will give you a random element from the array:
let enemy = enemies[Math.floor(Math.random()* enemies.length)];
Using underscore or lodash is another option:
let enemy = _.sample(enemies);
or
let enemy = enemies[_.random(enemies.length-1)];
const enemies = [
"Wizard Monster",
"Ice Golem",
"Electro Dragon",
"Fire Giant",
"Rahzar Mutant",
];
const amount_items_array = enemies.length;
const item_sorted = Math.floor(Math.random() * amount_items_array);
enemies.splice(item_sorted, 1)
console.log(enemies);
Related
This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 5 months ago.
So I have two Object Arrays that I need to make one Object Array.
var insertEpisode = [{
"show_id":new ObjectId(req.body.show_id),
"show_b":req.body.show_b,
"season":new Double(req.body.season),
"episode_no": new Double(req.body.episode_no),
"title": req.body.title,
"summary": podsummary,
"description": description,
"explicit":req.body.explicit,
"enclosureurl":filesToEpisode[0].file.enclosureurl,
"enclosurebyts": filesToEpisode[0].file.enclosurebyts,
"duration":new Double(filesToEpisode[0].file.duration),
}];
and if there is a image to go with the episode I have
if(image){
var image = [{"image":"this "}]
const array3 = insertEpisode.concat(image);
}
however that does not work. instead it added prints out like
[{"show_id":"6274a3a881cf417136a8a4ed","show_b":"insiderelationships","season":1,"episode_no":40,"title":"Test Title","summary":"A week ago a friend invited a couple of other couples over for dinner. Eventually, the food (but not the wine) was cleared off the table for what turned out to be some fierce Scrabbling.","description":"<![CDATA[<p>A week ago a friend invited aco</p>]]>","explicit":"false","enclosureurl":"URL TO mp3.mp3","enclosurebyts":"173080","duration":00:01:00},{"image":"this "}]
Instead it should look like
[{"show_id":"6274a3a881cf417136a8a4ed","show_b":"insiderelationships","season":1,"episode_no":40,"title":"Test Title","summary":"A week ago a friend invited a couple of other couples over for dinner. Eventually, the food (but not the wine) was cleared off the table for what turned out to be some fierce Scrabbling.","description":"<![CDATA[<p>A week ago a friend invited aco</p>]]>","explicit":"false","enclosureurl":"URL TO mp3.mp3","enclosurebyts":"173080","duration":00:01:00, "image":"this "}]
You can see the image part is joined into the first array.
You can use this:
if (image) {
var image = [{"image":"this "}]
const merged = {...insertEpisode, ...image};
}
const array3 = insertEpisode.map((item, index) => {
item = Object.assign({}, item, image[index]);
});
If you need to add an existing image url to your object, can you just assign a new property to the object of your insertEpisode array?
if (image) {
insertEpisode[0].image = 'this';
}
I would like to do a for loop with "CantAMS = 10" beeing the amount of loops I need and each time I loop to add 6 letters to my variables ColumnasAm, AMName, Ammail, and Check.
I have it writen now as an array of 10 X 1 and later loop through it, but I would like to create either a function or a for loop if possible where I add 6 letters to my variable each time it loops through it.
const CantAMS = 10
const ColumnasAm = ['A1:A', 'G1:G', 'M1:M','S1:S','Y1:Y','AE1:AE','AK1:AK','AQ1:AQ','AW1:AW','BC1:BC'];
const AMName = [ ws.getRange('A2').getValue(), ws.getRange('G2').getValue(), ws.getRange('M2').getValue(),ws.getRange('S2').getValue(),ws.getRange('Y2').getValue(),ws.getRange('AE2').getValue(),ws.getRange('AK2').getValue(),ws.getRange('AQ2').getValue(),ws.getRange('AW2').getValue(),ws.getRange('BC2').getValue()];
const Ammail = [ ws.getRange('B2').getValue(), ws.getRange('H2').getValue(), ws.getRange('N2').getValue(),ws.getRange('T2').getValue(),ws.getRange('Z2').getValue(), ws.getRange('AF2').getValue(),ws.getRange('AL2').getValue(),ws.getRange('AR2').getValue(),ws.getRange('AX2').getValue(),ws.getRange('BD2').getValue()];
const Check = [ ws.getRange('A5').getValue(), ws.getRange('G5').getValue(), ws.getRange('M5').getValue(),ws.getRange('S5').getValue(),ws.getRange('Y5').getValue(),ws.getRange('AE5').getValue(),ws.getRange('AK5').getValue(),ws.getRange('AQ5').getValue(),ws.getRange('AW5').getValue(),ws.getRange('BC5').getValue()];
const Columni = [1,7,13,19,25,31,37,43,49,55];
I'm super newbie in coding and I need help to achieve this code.
I'm trying to get a random item (in pairs) from an array and then remove it from this array until user gets to the last item or 60 days have gone from using the service (cookie?)... I have build a script with the help of other questions here in stackoverflow and here is my results so far.
`<script>
var randomizer = document.getElementById("getImgBut");
var dog1 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01F.jpg';
var dog2 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01B.jpg';
var dogpics=[dog1,dog2];
var yourPics = [
dogpics,
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/04F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/04B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/05F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/05B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/06F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/06B.jpg' ] //This array has 52 cards but I cutted it for example purposes
];
function get_random_number(array){
return Math.floor(Math.random() * array.length |0);
} // here is where I have tried to modify with other scripts like the one in this page https://stackoverflow.com/questions/38882487/select-random-item-from-array-remove-it-restart-once-array-is-empty with no success
randomizer.addEventListener("click", function() {
var rand_number = get_random_number(yourPics);
console.log(rand_number);
document.getElementById('img1').src = yourPics[rand_number][0];
document.getElementById('img2').src = yourPics[rand_number][1];
});
var card = document.querySelector('.card');
card.addEventListener( 'click', function() {
card.classList.toggle('is-flipped');
});
</script>`
Thank you for your help!
I don't fully understand what you mean by "remove in pairs", but I'll answer presuming you mean you wish to remove the image ending in 02F.jpg at the same time as removing the image ending in 02B.jpg, and then 03F.jpg at the same time as 03B.jpg.
The solution to this that I will propose is that we will structure your data a bit differently to begin with. That is, if those images, the "B image" and "F image" are linked, we could keep them in the same `javascript object. This would look like:
var yourPics = [
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg'
},
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg'
}...]
This would then be an array of objects, rather than strings. We can access the bImage property of an object with just
myObject = yourPics[0]
myObject.bImage
We could delete one of those objects those at random via splice.
myRandomlyRemovedObject = yourPics.splice(myIndexToDeleteFrom, 1) would remove 1 object from yourPics at position of myIndexToDeleteFrom, which you presumably would choose randomly. myRandomlyRemovedObject would be assigned to the one object we removed.
I think this object based approach is safer since you will know for a fact that you will removed both matching strings at the same time.
Alright so I stuck on the code reading docs.
Iam starting with JS so go easy one me =].
I've got and array calld Area
which contains few arguments
let Area = ["Kanig Village", "Fort Chune", "Shadowy Heights", ...];
I cannot change this array till specific part of my code is executed but after I wish to add to every position another value. How to I do that to get exacly like that :
let Area = ["Kanig Village 14:30", "Fort Chune 15:30", "Shadowy Heights 16:30", ...];
I THINK this is what you want to do:
https://jsfiddle.net/wxzrpjeL/
//Declare 2 arrays
let Area = ["Kanig Village", "Fort Chune", "Shadowy Heights"];
let b = ["1", "2", "3"];
//Execute a function for each element in the Area array
Area.forEach(function(val, i) {
//The function appends a space, and the corresponding element in the second array
Area[i] += " " + b[i];
});
// just to illustrate the result, throw the result to the screen as a string...
alert(Area.toString());
i hope this is your answer
let Area = ["Kanig Village", "Fort Chune", "Shadowy Heights"];
for(i=0;i<Area.length;i++)
{
var hour=14+i;
Area[i]+=" "+hour+" : 30";
}
This question already has answers here:
How to store objects in HTML5 localStorage/sessionStorage
(24 answers)
Closed 7 years ago.
I have a number of drivers saved in objects:
function Driver(draw, name) {
this.draw = draw;
this.name = name;
}
Now, the number of drivers could change depending on how my form is used. It could be 5, it could be 60.
My understanding of using HTML5 Session storage is the syntax goes like this:
sessionStorage.setItem('name', value).
What I would like to do is have the ability to save them with the names driver1, driver2, driver, 3, etc. But, the numbers won't be consecutive and may include any amount up to 60.
Here's how I tried to do it, but it isn't working.
$('.print').click(function () {
for (var i = 0; i < 60; i++){
var name3 = "."+"driver"+i;
if (typeof Driver[name3] != "undefined") {
console.log(name3);
console.log(Driver[name3]);
sessionStorage.setItem(Driver[name3], JSON.stringify(Driver[name3]));
console.log(sessionStorage.getItem(Driver[name3]));
entries[entries.length] = name3;
}
console.log(entries);
sessionStorage.setItem('entries', JSON.stringify(entries));
};
What I tried to do is set a value for var name3, and then set the name of the session storage file to that value. It's pretty obvious to me I can't do that. I can't figure out another way of achieving my goal?
FYI, my attempt to sessionStorage 'Entries' is working perfectly.
Here's my entire project if you need to fiddle with it: http://precisioncomputerservices.com/slideways/index.html
It was posted as a comment but it's the answer.
Store everything in an array.
var allMyDrivers = [...];
sessionStorage["drivers"] = JSON.stringify(allMyDrivers);
var driversLater = JSON.parse(sessionStorage["drivers"]);
Because your constructors arguments are retrievable from your Objects, you can just pass these through the constructor again in your retreival function
function storeDrivers(arr) {
sessionStorage.setItem('drivers', JSON.stringify(arr));
}
function retrieveDrivers() {
var arr = JSON.parse(sessionStorage.getItem('drivers')) || [];
return arr.map(function (e) {return new Driver(e.draw, e.name);});
}
function forgetDrivers() {
sessionStorage.removeItem('drivers');
}
storeDrivers([
new Driver('foo', 'bar'),
new Driver('fizz', 'buzz')
]);
retrieveDrivers();
// [
// Driver {draw: "foo", name: "bar"},
// Driver {draw: "fizz", name: "buzz"}
// ]
forgetDrivers();