innerHTML returns undefined - JavaScript - javascript

I'm creating a game on the web for my studies. I need to create a card game where each card has its own data (number and power name), data is taken from data.txt and put in an array that is then randomized. data.txt looks something like this:
0
Bored cat
-8
Biting
-10
Scratching
Play() function scrambles the deck when the PLAY button is pressed.
Once all cards are randomized I call a function addCardCat() which should create a card div with h1 and h3 tags. In h1 tag innerHTML should be a number, and h3 should be the power name, however, I always get returned undefined.
What could be the issue?
JS CODE
let counter = 0;
var deck = [];
// ----------READING----------//
let fs = require('fs');
let data = fs.readFileSync('data.txt', 'utf8').split('\r\n');
// ----------RANDOM NUMBER GENERATOR----------//
let numberArray = Array.from(Array(54).keys())
// ----------ARRAY SCRAMBLE---------//
function scrambleArray(array){
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle...
while (currentIndex != 0){
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
// ----------PLAYING DECK----------//
function scrambleDeck(array){
for(var i = 0; i < 54; i++){
var j = numberArray[i];
array.push(data[j*2]);
array.push(data[j*2+1]);
}
return array;
}
// ----------ADD CARD----------//
function addCardCat(number, power) {
counter++;
var newDiv = document.createElement("div");
newDiv.className += " cat__card";
newDiv.id = 'card-' +counter;
// newDiv.onclick = removeCardCat();
// newDiv.onclick = function() { alert('blah'); };
document.getElementById('cat').appendChild(newDiv);
var newH1 = document.createElement("h1");
var newH3 = document.createElement("h3");
document.getElementById('card-' +counter).appendChild(newH1);
document.getElementById('card-' +counter).appendChild(newH3);
newH1.innerHTML = number;
newH3.innerHTML = power;
return number, power;
}
// ----------START GAME----------//
function play() {
document.getElementById("play").style.display = "none";
scrambleArray(numberArray);
scrambleDeck(deck);
}```

It's hard to tell with the subminimal code provided, but it is likely that this return number, power; is causing your issue.
The return statement ends function execution and specifies a value to be returned to the function caller.
MDN
The return statement will only return a single value. You cannot use a comma-separated list. See the first snippet below for a demonstration of what happens if you use a comma-separated list.
let x = function(number, power) {
//Do stuff
return number, power;
}
console.log(x(2, 5));
Notice that you only got back the last value in the comma-separated list.
You can, however, wrap the 2 values in an array or object, for example, and then return the array or object. You can then use the appropriate destructuring method to extract the 2 values from the array or object.
Like this:
let x = function(number, power) {
//Do stuff
return [number, power];
}
console.log(x(2, 5));
That being said, it does seem odd that you are returning the same values you passed to the function as arguments without modifying them in any way.
Depending on what you do with the returned values, which unfortunately you don't show in your question, you will need to do one of the following:
Use the method I described.
Return a valid single value (including true or false) as needed.
Eliminate the return statement.

Related

Pick random index and change till all unique are done then restart

I have image gallery with 6 image slot and i have a array with n no of image object like this
"src" : {
"1x" : "/clients/Logo-1.png",
"2x" : "/clients/Logo-1#2x.png",
"3x" : "/clients/tLogo-1#3x.png"
},
"alt" : "xyz"
}
what i want is to show random 6 image from array and then every 5 sec randomly one slot need to be change and get update with a new unique image which must not be in first 6 slot and then after finishing all it should continue the 5 sec change with a new unique image which must not be in those 6 slot.
what i have tried
let randomList = this.shuffleArray(this.LogosListObj);
let FirstSixImg = randomList.slice(0, 6);
let LeftAllImg = randomList.slice(6 + 1);
let RandomIndex = this.randomNoRepeats([0,1,2,3,4,5])
let RandomSecoundImg = this.randomNoRepeats(Array.apply(null, new Array(LeftAllImg.length)).map(function(el, i) {return i}))
let RandomFirstImg = this.randomNoRepeats(Array.apply(null, new Array(FirstSixImg.length)).map(function(el, i) {return i}))
this.ImageToShowList = [...FirstSixImg];
let checkArr = [];
let checkArr2 = [];
let flag = false;
let index,secndIndex,thirdIndex;
const LogoChange = (arr) =>{
if(!flag) {
secndIndex = RandomSecoundImg();
console.log('1st',secndIndex)
if(checkArr.indexOf(secndIndex) == -1) {
index = RandomIndex();
checkArr.push(secndIndex)
ctl.ImageToShowList[index] = {};
ctl.ImageToShowList[index] = LeftAllImg[secndIndex];
Vue.set(ctl.ImageToShowList, index, LeftAllImg[secndIndex])
ctl.PreviousImgObj = {...LeftAllImg[secndIndex]};
} else {
flag = true;
checkArr = [];
}
}
if(flag) {
thirdIndex = RandomFirstImg();
console.log('2nd',thirdIndex)
if(checkArr2.indexOf(thirdIndex) == -1) {
checkArr2.push(thirdIndex)
ctl.ImageToShowList[thirdIndex] = {};
ctl.ImageToShowList[thirdIndex] = FirstSixImg[thirdIndex];
Vue.set(ctl.ImageToShowList, thirdIndex, FirstSixImg[thirdIndex])
ctl.PreviousImgObj = {...FirstSixImg[thirdIndex]};
}else {
flag = false;
checkArr2 = [];
LogoChange();
}
}
}
setInterval(()=>{
LogoChange();
}, 1000);
where randomNoRepeats is
randomNoRepeats : (array) => {
var copy = array.slice(0);
return function() {
if (copy.length < 1) { copy = array.slice(0); }
var index = Math.floor(Math.random() * copy.length);
var item = copy[index];
copy.splice(index, 1);
return item;
};
and shuffleArray is
shuffleArray : (array) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
},
this.ImageToShowList is used in html part to display
Any help with logic or change will be appreciate.
I have my example fiddle here, but this is the breakdown:
Your data would look something like this:
let galleryPool = [
{
"src" : {
"1x" : "/clients/Logo-1.png",
"2x" : "/clients/Logo-1#2x.png",
"3x" : "/clients/tLogo-1#3x.png"
},
"alt" : "xyz",
"color": "red"
},
...
]
(I added a color property so you could see the changes since I don't actually have any images.)
The first thing I do is drop in my handy-dandy Fisher–Yates shuffle, since this is a great way to get a random element out of an array.
Array.prototype.shuffle = function() {
let currentIndex = this.length, randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[this[currentIndex], this[randomIndex]] = [this[randomIndex], this[currentIndex]];
}
return this;
}
I initialize the gallery first, and set up the 5-second timeout to change images in the gallery.
let displayedGallery = []
initialGallerySetup();
function initialGallerySetup() {
let galleryContainer = document.getElementById("gallery-container")
galleryPool.shuffle()
displayedGallery = galleryPool.splice(0, 6)
for(let index = 0; index < displayedGallery.length; index++) {
let data = displayedGallery[index]
galleryContainer.appendChild(generateGalleryItem(data))
}
galleryTickUpdate()
}
this function makes an img dom element I can then add to the container. I'm using your src here but you can change whatever values in here to alter how all of the images in the gallery are displayed.
function generateGalleryItem(data) {
let item = document.createElement("img")
item.style.backgroundColor = data.color
item.src = data.src[0]
item.className = "gallery-item"
return item
}
This function calls itself every 5 seconds, and will pick a random item from the gallery to swap with another item not currently displayed.
function galleryTickUpdate() {
setTimeout(() => {
let randomIndex = Math.floor(displayedGallery.length * Math.random())
swapItemAtIndex(randomIndex)
galleryTickUpdate()
},5000)
}
Here's the magic. I grab the randomly chosen item out of the displayed gallery items, pick a new item from the unused gallery pool items, put the old one back in the pool and the new one gets pushed back into the gallery display in the same spot.
function swapItemAtIndex(index) {
let galleryContainer = document.getElementById("gallery-container")
let displaySlot = galleryContainer.children[index]
let returning = displayedGallery[index]
galleryPool.shuffle()
let newDisplay = galleryPool.pop();
displayedGallery[index] = newDisplay
galleryPool.push(returning)
galleryContainer.insertBefore(generateGalleryItem(newDisplay), displaySlot)
galleryContainer.removeChild(displaySlot)
}
If you want to enforce running through the whole array, just check when the galleryPool array is empty, then repopulate it and re-run the init function. Otherwise, this will happily run forever.
here is a simple script. you will need the following
pool this will contain all possible values you would like
single function to update the show array
Test Here
I've tried to put as much comments as possible
// Pool with all possible images (you may use any type of text as long as each value is unique)
const pool = [
"1.png",
"2.png",
"3.png",
"4.png",
"5.png",
"6.png",
"7.png",
"8.png",
"9.png",
"10.png",
];
// this will store the "6" unique elements which you will be displaying
let show = [];
// get the first 6 random but unique elements. we will monitor the length of the `show` array
while(show.length < 6){
// randomly sort the pool and get the first element of the sorted array and store it into a `pooled` variable.
let pooled = pool.sort(() => 0.5 - Math.random())[0];
// check if the pooled value exists in the `show` array if it doesnt then add it and repeat the loop till all 6 slots are filled with unique values
if(!show.includes(pooled)){
// add `pooled` item to the `show` array
show.push(pooled);
}
}
// do the same as the above with a slight change, of only replacing one till all are unique.
function after5Mins(){
// get a new random item from the pool
let newPoolItem = pool.sort(() => 0.5 - Math.random())[0];
// using a while loop check if the new `pool item` is in the show array, if not then skip and add it
while(show.includes(newPoolItem)){
newPoolItem = pool.sort(() => 0.5 - Math.random())[0]; // set the pool item to a random one, then loop and check, follow previous comment
}
// once a new un used item is found, then assign it to a random position
show[Math.floor(Math.random()*show.length)] = newPoolItem;
}
// call the after 5 mintes using
setTimeout(()=>{
after5Mins();
}, 300000);

Define an array just once and change it without defining it again in JavaScript

I want to define an array in a line of the program, for example, as follows:
var a = [2,5];
//In the next steps, I want to increase the array elements as follows:
a[0] += 2;
a[1] += 2;
//And I want the array to increase intermittently at the output of the program, as follows:
a = [4,7]
a = [6,9]
a = [8,11]
//....
But in reality this does not happen because in the first line of the program, the array is defined again and again.
And the output is always as follows: a = [4,7];
Is there a way to initialize the a array as [2,5] only once?
There are many ways to do this.
This is a very simple way if you want to increase it a fixed number of times:
let a = [2,5];
for (let i=0;i<5;i++) {
a=a.map(element=>element+2);
console.log(a);
}
Using a nested function/closure as shown in Lonnie Best's answer
Or you can also use a generator function:
function * arrayIncreaser(initialArray, num) {
let a = initialArray;
while (true) {
a = a.map(element=>element+num)
yield a;
}
}
const increaser = arrayIncreaser([2,5],2)
console.log(increaser.next().value);
console.log(increaser.next().value);
console.log(increaser.next().value);
Here, I use a closure. The array is created once and modified each time you call increase():
function createIncreaseFunction()
{
const a = [2,5];
function increase()
{
a[0] += 2;
a[1] += 2;
return a;
}
return increase;
}
let increase = createIncreaseFunction();
console.log(increase()); // [4,7]
console.log(increase()); // [6,9]
console.log(increase()); // [8,11]
// increase() modifies the values in the array,
// but the same array is returned each time:
console.log(increase() === increase()); // true

Most frequently occuring number (mode) in a list - want to get only the highest value

I'm trying to get whatever number is the most frequently occuring number in an array, so for an array containing 1,2,10,5,1 the result should be 1. The code I wrote returns me the frequency for each number, so 1 occurs twice, 2 occurs once, 10 occurs once etc. Any suggestions how I can fix my result?
function mode(arr) {
var uniqNum = {};
var numCounter = function(num, counter) {
if(!uniqNum.hasOwnProperty(num)) {
uniqNum[num] = 1;
} else {
uniqNum[num] ++;
}
};
arr.forEach(numCounter);
return uniqNum;
}
I've kept your code unchanged and added some extra statements. Here is the demo: http://codepen.io/PiotrBerebecki/pen/rrdxRo
function mode(arr) {
var uniqNum = {};
var numCounter = function(num, counter) {
if(!uniqNum.hasOwnProperty(num)) {
uniqNum[num] = 1;
} else {
uniqNum[num] ++;
}
};
arr.forEach(numCounter);
return Object.keys(uniqNum)
.sort((a,b) => uniqNum[b] - uniqNum[a]) // sort by frequency
.filter((val,ind,array) => uniqNum[array[0]] == uniqNum[val]) // leave only most frequent
.map(val => Number(val)); // convert text to number
}
console.log( JSON.stringify(mode([3,3,2,4,4])) ) // [3,4]
console.log( JSON.stringify(mode([2,4,3,3])) ) // [3]
I think it could be done only with a little modification to your forEach loop and the assistance of another auxiliary data structure:
function mode(arr) {
var freq = [], uniqNum = {}, i;
arr.forEach(function (num) {
uniqNum[num] = i = (uniqNum[num] || 0) + 1;
freq[i] = (freq[i] || []).concat(num);
});
return freq[freq.length - 1];
}
console.log(mode([1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 6, 7, 1, 6]));
With only one iteration over all the elements of the array we can gather enough information to print out the result:
uniqNum is the set you created to gather info about the element's frequency.
freq will be an array which last element will contain an array with the elements of higher frequency.
Fiddle. Hope it helps.
First we want to make an array where we count the number of occurrences of a certain value up to that point.
Then we use the reduce function to return an array of values read from the original array for the indexes whose values have the current max appearances. We redefine max and empty the final output array of modes (if new max is established) as we go along. We want this to be a collection in case there is a tie for maximum appearances.
Additional advantage of the below is that it doesn't require sort which is more expensive o(nlog n) and keeps the time complexity down to just linear. I also wanted to keep the functions used down to only two (map and reduce) as it is all that is need in this case.
edit: fixed a major bug uniqNum[e] += 1 instead of uniqNum[e] + 1 which went unnoticed as my initial case array was still returning expected result. Also made the syntax more concise in favor of more comments.
var arr = [1,2,10,5,1,5,2,2,5,3,3];
//global max to keep track of which value has most appearances.
var max = -1;
var uniqNum = {};
var modeArray = arr.map(function(e) {
//create array that counts appearances of the value up to that point starting from beginning of the input arr array.
if(!uniqNum.hasOwnProperty(e)) {
uniqNum[e] = 1;
return 1;
} else {
return uniqNum[e] += 1;
}
//reduce the above appearance count array into an array that only contains values of the modes
}).reduce(function (modes, e1, i) {
//if max gets beaten then redefine the mode array to only include the new max appearance value.
if(e1 > max){
//redefining max
max = e1;
//returning only the new max element
return [arr[i]];
//if its a tie we still want to include the current value but we don't want to empty the array.
}else if(e1 == max){
//append onto the modes array the co-max value
return[...modes, arr[i]];
}
return modes;
},[]);
alert(modeArray);
Here is a test you can run of my solution against #acontell. In my browser (Chrome with V8) my solution was around three-four times faster for arrays with large number of repeating values and even bigger advantage with distributions with lower number of repeating values. #acontell 's is a cleaner looking solution for sure, but definitely not faster in execution.
var arr = [];
for(var i=0; i < 100000; i++){
arr.push(Math.floor(Math.random() * (100 - 1)) + 1);
}
console.time("test");
test();
function test(){
var max = -1;
var uniqNum = {};
var modeArray = arr.map(function(e) {
//create array that counts appearances of the value up to that point starting from beginning of the input arr array.
if(!uniqNum.hasOwnProperty(e)) {
uniqNum[e] = 1;
return 1;
} else {
return uniqNum[e] += 1;
}
//reduce the above appearance count array into an array that only contains values of the modes
}).reduce(function (modes, e1, i) {
//if max gets beaten then redefine the mode array to only include the new max appearance value.
if(e1 > max){
//redefining max
max = e1;
//returning only the new max element
return [arr[i]];
//if its a tie we still want to include the current value but we don't want to empty the array.
}else if(e1 == max){
//append onto the modes array the co-max value
modes.push(arr[i])
return modes;
}
return modes;
},[]);
}
console.timeEnd("test");
console.time("test1");
test1();
function test1 () {
var freq = [],
uniqNum = {},
i;
arr.forEach(function(num) {
uniqNum[num] = i = (uniqNum[num] || 0) + 1;
freq[i] = (freq[i] || []).concat(num);
});
return freq[freq.length - 1];
}
console.timeEnd("test1");
I've tried as an exercise to solve this with native js functions.
var arr = [1,2,10,5,1];
// groupBy number
var x = arr.reduce(
function(ac, cur){
ac[cur]?(ac[cur] = ac[cur] + 1):ac[cur] = 1;
return ac;
}, {}
);
// sort in order of frequencies
var res = Object.keys(x).sort(
function(a,b){ return x[a] < x[b]}
);
res[0] has the most frequent element

How to pick a random property from an object without repeating after multiple calls?

I'm trying to pick a random film from an object containing film objects. I need to be able to call the function repeatedly getting distinct results until every film has been used.
I have this function, but it doesn't work because the outer function returns with nothing even if the inner function calls itself because the result is not unique.
var watchedFilms = [];
$scope.watchedFilms = watchedFilms;
var getRandomFilm = function(movies) {
var moviesLength = Object.keys(movies).length;
function doPick() {
var pick = pickRandomProperty(movies);
var distinct = true;
for (var i = 0;i < watchedFilms.length; i += 1) {
if (watchedFilms[i]===pick.title) {
distinct = false;
if (watchedFilms.length === moviesLength) {
watchedFilms = [];
}
}
}
if (distinct === true) {
watchedFilms.push(pick.title);
return pick;
}
if (distinct === false) {
console.log(pick.title+' has already been picked');
doPick();
}
};
return doPick();
}
T.J. Crowder already gave a great answer, however I wanted to show an alternative way of solving the problem using OO.
You could create an object that wraps over an array and makes sure that a random unused item is returned everytime. The version I created is cyclic, which means that it infinitely loops over the collection, but if you want to stop the cycle, you can just track how many movies were chosen and stop once you reached the total number of movies.
function CyclicRandomIterator(list) {
this.list = list;
this.usedIndexes = {};
this.displayedCount = 0;
}
CyclicRandomIterator.prototype.next = function () {
var len = this.list.length,
usedIndexes = this.usedIndexes,
lastBatchIndex = this.lastBatchIndex,
denyLastBatchIndex = this.displayedCount !== len - 1,
index;
if (this.displayedCount === len) {
lastBatchIndex = this.lastBatchIndex = this.lastIndex;
usedIndexes = this.usedIndexes = {};
this.displayedCount = 0;
}
do index = Math.floor(Math.random() * len);
while (usedIndexes[index] || (lastBatchIndex === index && denyLastBatchIndex));
this.displayedCount++;
usedIndexes[this.lastIndex = index] = true;
return this.list[index];
};
Then you can simply do something like:
var randomMovies = new CyclicRandomIterator(Object.keys(movies));
var randomMovie = movies[randomMovies.next()];
Note that the advantage of my implementation if you are cycling through items is that the same item will never be returned twice in a row, even at the beginning of a new cycle.
Update: You've said you can modify the film objects, so that simplifies things:
var getRandomFilm = function(movies) {
var keys = Object.keys(movies);
var keyCount = keys.length;
var candidate;
var counter = keyCount * 2;
// Try a random pick
while (--counter) {
candidate = movies[keys[Math.floor(Math.random() * keyCount)]];
if (!candidate.watched) {
candidate.watched = true;
return candidate;
}
}
// We've done two full count loops and not found one, find the
// *first* one we haven't watched, or of course return null if
// they've all been watched
for (counter = 0; counter < keyCount; ++counter) {
candidate = movies[keys[counter]];
if (!candidate.watched) {
candidate.watched = true;
return candidate;
}
}
return null;
}
This has the advantage that it doesn't matter if you call it with the same movies object or not.
Note the safety valve. Basically, as the number of watched films approaches the total number of films, our odds of picking a candidate at random get smaller. So if we've failed to do that after looping for twice as many iterations as there are films, we give up and just pick the first, if any.
Original (which doesn't modify film objects)
If you can't modify the film objects, you do still need the watchedFilms array, but it's fairly simple:
var watchedFilms = [];
$scope.watchedFilms = watchedFilms;
var getRandomFilm = function(movies) {
var keys = Object.keys(movies);
var keyCount = keys.length;
var candidate;
if (watchedFilms.length >= keyCount) {
return null;
}
while (true) {
candidate = movies[keys[Math.floor(Math.random() * keyCount)]];
if (watchedFilms.indexOf(candidate) === -1) {
watchedFilms.push(candidate);
return candidate;
}
}
}
Note that like your code, this assumes getRandomFilm is called with the same movies object each time.

Knockout: More confusion with indexOf returning -1

Background
I'm attempting to check the existence of a value in array A in a second array, B. Each value is an observable number. Each observable number is contained in an observable array. The comparison always returns -1, which is known to be incorrect (insofar as values in A and B overlap). Therefore, there's something wrong with my logic or syntax, but I have not been able to figure out where.
JSBin (full project): http://jsbin.com/fehoq/190/edit
JS
//set up my two arrays that will be compared
this.scores = ko.observableArray();
//lowest is given values from another method that splices from scores
this.lowest = ko.observableArray();
//computes and returns mean of array less values in lowest
this.mean = (function(scores,i) {
var m = 0;
var count = 0;
ko.utils.arrayForEach(_this.scores(), function(score) {
if (!isNaN(parseFloat(score()))) {
//check values
console.log(score());
// always returns -1
console.log(_this.lowest.indexOf(score()));
//this returns an error, 'not a function'
console.log(_this.lowest()[i]());
//this returns undefined
console.log(_this.lowest()[i]);
//only do math if score() isn't in lowest
// again, always returns -1, so not a good check
if (_this.lowest.indexOf(score())<0) {
m += parseFloat(score());
count += 1;
}
}
});
// rest of the math
if (count) {
m = m / count;
return m.toFixed(2);
} else {
return 'N/A';
}
});
Update
#Major Byte noted that mean() is calculated before anything gets pushed to lowest, hence why I get undefined. If this is true, then what might be the best way to ensure that mean() will update based on changes to lowest?
You really just could use a computed for the mean
this.mean = ko.computed(
function() {
var sum = 0;
var count = 0;
var n = 0;
for(n;n < _this.scores().length;n++)
{
var score = _this.scores()[n];
if (_this.lowest.indexOf(score)<0) {
sum += parseFloat(score());
count++;
}
}
if (count > 0) {
sum = sum / count;
return sum.toFixed(2);
} else {
return 'N/A';
}
});
this will trigger when you add to lower(), scores() and change scores().
obligatory jsfiddle.
Update:
Forgot to mention that I change something crucial as well. From you original code:
this.dropLowestScores = function() {
ko.utils.arrayForEach(_this.students(), function(student){
var comparator = function(a,b){
if(a()<b()){
return 1;
} else if(a() > b()){
return -1;
} else {
return 0;
}
};
var tmp = student.scores().sort(comparator).slice(0);
student.lowest = ko.observableArray(tmp.splice((tmp.length-2),tmp.length-1));
});
};
apart from moving the comparator outside of dropLowestScores function, I changed the line:
student.lowest = ko.observableArray(tmp.splice((tmp.length-2),tmp.length-1));
to
student.lowest(tmp.splice((tmp.length-2),tmp.length-1));
student.lowest is an observable array, no need to define it as an observableArray again, in fact that actually breaks the computed mean. (The correction for Drop Lowest Scores as per my previous comment is left out here).

Categories