Randomize Keyword Links - javascript

I'm currently looking for a method to display five keywords/links at a time from a total of about 50 at random. So for example, a function to grab a keyword and the links to go with them at random, and have them display in a webpage according to what I prefer with CSS.
It sounds simple enough but I just can't seem to find the answer I'm looking for. Any help is appreciated! Thanks!

Something like that?
function getRandomLinks(count,links){
var randomlinks = [];
for(var i = 0; i < count; i++){
randomlinks.push(links.splice(Math.floor(Math.random()*links.length),1)[0]);
}
return randomlinks;
}
console.log(getRandomLinks(2,["link1","link2","link3","link4"]));

Related

Trying to make sense of "this" in my javascript code (one thing works, the other doesn't)

I've been trying to learn javascript by refactoring some Jquery examples in a book into javascript. In the following code I add a click listener to a tab and make it change to active when the user clicks on the tab.
var tabs = document.querySelectorAll(".tabs a span");
var content = document.querySelectorAll("main .content li");
for (var tabNumber = 0; tabNumber <= 2; tabNumber++) {
tabs[tabNumber].addEventListener("click", function (event) {
for (var i = 0; i < tabs.length; i++) {
tabs[i].classList.remove("active");
}
tabs[tabNumber].classList.add("active");
for (var i = 0; i < content.length; i++) {
content[i].innerHTML = "";
}
event.preventDefault();
});
}
This returns an undefined error when I run it. However, I tried replacing tabs[tabNumber].classList.add("active") with this.classList.add("active") and it worked.
Why doesn't the previous code work? As far as I can see they are referring to the same thing, and tabs[tabNumber] should work since at that point in the code it is tabs[0].
If use this, I think it's better and a more polished solution. If you still want to use tabNumber, it's probably evaluating to 3 in every click callback, because it's the number after the last iteration, and you don't have a tabs[3] position.
So, you just have to make a closure of the tabNumber variable.
I guess other answers told you why tabs[tabNumber] does not work (because it comes from the score of the for loop and so, is always equal to the greater value of tabNumber).
That's why I would recommend using a .forEach loop. Careful though because it doesn't work on arrays of DOM nodes produced by document.querySelectorAll(), but you can use:
// ES6
Array.from(document.querySelectorAll('...'))
// ES5
[].slice.call(document.querySelectorAll('...'))
Anyway, I made a simplified working demo of your code.
Note that I save the currently active tab in a variable, to prevent another for loop. You could also do:
document.querySelector('.active').classList.remove('active')
But I like to reduce the amount of DOM reading.
Good luck for your apprentissage, re-writing some jQuery code into Vanilla JS seems like a good method, and you might acquire a far better comprehension of JavaScript.

Array adds dimension when randomized

Allo'
I'm working on a little project of mine and part of it involves taking a two dimensional array already created and randomizing it.
So I have something which looks like this:
foo = [[1,2],[3,4],[5,6],[7,8]];
randomizeFoo = function(){
var randomizedFoo = [];
newFoo = foo;
for(i = 0; i < newFoo.length; i++){
count = Math.random() * newFoo.length;
randomizedFoo.push(newFoo.slice(count, count + 1));
}
return randomizedFoo;
};
This does indeed randomize the array but I end up with something like this:
randomizedFoo = [[[7,8]],[[1,2]],[[5,6]],[[3,4]]]
My nice neat 2D array is now a 3D array with the lowest level arrays now burred under an extra level. I realize that this is not really that big a deal and the rest of my code just needs to compensate but it bugs me for 2 reasons:
It's extra complexity and that's never good.
I don't like my code doing things without me knowing the reason why.
Anybody have any ideas as to why it's doing this? I put a 2D array in, I want a 2D array back out again.
It's because you are using slice. Just use count as the index into foo. As in : randomizedFoo.push(foo[count]);
Make sure you make count an int first.
You can take the script from this answer and use map with it:
foo = range(0, foo.length-1, true).map(function(i) {
return foo[i];
});
Demo: http://jsbin.com/ayepeh/1/edit (ctrl + enter to refresh)

Google Docs - spreadsheet loop

This one might be a bit basic and easy to answer, but I've been pulling out my hair for a while now!
I've built the following code - which is semi-pseudo as I can't find the right way to make things work!
var s = "Test";
function onEdit(event)
{
var ss = event.source.getActiveSheet();
var r = event.source.getActiveRange();
if (ss.getName() == s)
{
results = {"Currently On": 0, "Next Up": 0, "On Hold": 0, "Waiting on someone else": 0, "zDone": 0};
last = ss.getMaxRows();
start = ss.getRange("F3:"+last).getValues();
var output = "J11";
for (x=0;x<start.length;x++)
{
results[start[x]]++;
}
for (y=0;y<results.length;y++)
{
row = ss.getRow(output);
row.value = results[y];
output++;
}
}
}
I've got an example of the data in this image
The basic idea is to run through all the possible categories of each task and keep a numeric list on the side of how many of each there are. I'd also like to make it dynamic (so I don't have to hard code in the list of categories) but I'm more interested in just making it work for the moment.
The Google Apps debugger is very frustrating!
Thanks for your help all!
Firstly, this particular use case would be easily achievable with a spreadsheet formula, eg:
=QUERY(A2:F;"select F, count(A) where F != '' group by F label count(A) 'Count'";1)
but there may be a reason why you want to do this with GAS.
So secondly, this is where I think there may be some syntax issues:
last = ss.getMaxRows();
I would just use var last = ss.getLastRow() here.
start = ss.getRange("F3:"+last).getValues();
The range reference would evaluate to something like "F3:100", which is a valid reference in GSheets (don't know about whether GAS can handle it), but nevertheless you really want something like "F3:F100", so I would use var start = ss.getRange("F3:F"+last).getValues();.
results[start[x]]++;
When you create an array from a getValues() call it is a 2D array, so you would need to use results[start[x][0]]++;.
With the next loop and the output variable, I must admit I'm a bit lost with what you're doing there. How did you want your result table laid out?
You have
output = "J11";
And then you do
ss.getRow(output);
output++;
This is invalid.First of all, ss is a Sheet under which there is not getRow method. So, what you should really be doing is something like this
var row = 11 ;
var col = 10 ; //Col J
for (y=0;y<results.length;y++)
{
ss.getRange(row,col,1,1).setValue(results[y]);
row++:
}
Like AdamL, I suggest that this is better handled within the native capability of the spreadsheet. Seems to me that you want a pivot table, which would update dynamically. Alternatively a formula like =countif(F:F,"Currently On" ) would meet your immediate request. =Unique(F:F) will give you the list of categories in an array

Reading out a JS object

I have been messing around for a project I'm working on with arrays in JS. However, since this didn't work out, I had to turn to objects. Never having used these, I'm wondering about something fairly simple, yet complicated to me. I have the following code:
var ticket_amount = {};
var days = $(".t_days_" + ticket_id).val().split(',');
for(var i = 0; i < days.length; i++)
{
if (! ticket_amount[days[i]])
{
ticket_amount[days[i]] = 0;
};
ticket_amount[days[i]] += num_tickets;
}
This gives me my output as follows:
I now want to use the information in this object to display some more information. More specifically, I need to get both the date and the ticketnumber out so I can work with them in jQuery. I'm not sure how to do this, though.
I've tried stuff like:
for(tickets in ticket_amount) { }, for(var i = 0; i < ticket_amount.length; i++) {}, but none of these options seem to work. How do I get the information out in this specific case? Thanks a lot.
I won't be on the computer after posting this so I won't be able to answer to any questions for now, but I will find time for it tomorrow. Thanks in advance.
You were almost correct. This would print the data you need, for example.
for(ticket in ticket_amount)
{
console.log("Ticket:" + ticket + " amount: " + ticket_amount[ticket]);
}
EDIT:
of course, ticket in the above example should have been named just a tad better :)
for(day in ticket_amount){
// Here day contains the day, and ticket_amount[day] contains the number of tickets
alert(day+': '+ticket_amount[day]);
}

Searching an array for a substring in Javascript

I have searched across the web though have not had any luck in correcting my issue. What I want to do is search an array for a substring and return the result. An example of the array is like this:
the_array = ["PP: com.package.id, NN: Package Name","PP: com.another.id, NN: Another Name"];
What I want to do is search the_array for com.package.id making sure that it appears between the "PP:" and ",". Also please note that the array will contain several thousand values. Hope you can help, thank you.
Easy way:
the_array.join("|").indexOf([str]) >= 0;
Other ways would be to loop thru the array using .each() or a simple for loop
Array.prototype.each = function(callback){
for (var i = 0; i < this.length; i++){
callback(this[i]);
}
}
the_array.each(function(elem){
console.log(elem.indexOf('<searchString goes here>'));
});

Categories

Resources