How to alert a single element from an array in javascript? - javascript

Hello everyone I am new here and I am just starting to learn javascript.
I need to come up with a piece off code that alerts a single random element from an array. I have managed to come up with the random element but it alerts all ten of them from the array. While I need t to alert a single one and stop.
This is what I have so far.
var myList = new Array("gusty", "long", "tremendous", "play", "white",
"literate", "baboon", "dusty", "government", "cheer");
for(i = 0; i < myList.length; i++)
{
var y = Math.floor(Math.random() * 10);
alert(myList[y]);
}
So when I load this in a browser I get ten random words. But I just want one. I tired putting the var inside the alert but that didn't do anything.

Just remove the for loop. Since you are referring to the element from array using an index (myList[y]), you don't require a for loop there.
var myList = new Array("gusty", "long", "tremendous", "play", "white",
"literate", "baboon", "dusty", "government", "cheer");
var y = Math.floor(Math.random() * 10);
alert(myList[y]);
You would generally use a for loop to repeat a certain task. So in your original code, you are generating 10 random numbers, and thus accessing 10 random items from the array. If you need just one, you can simply remove the loop.

If you want to alert just one, you've no need for a loop. The loop is causing a random value to be selected each time and alerted.
There are some other optimisations you can make.
//we don't normally use new Array() without good reason; use an array literal
//i.e. [1, 2, 3, 'foo'] instead
var myList = ["gusty", "long", "tremendous", "play", "white",
"literate", "baboon", "dusty", "government", "cheer"];
//remove the loop - and instead of hard-coding 10, let's read the actual length
var y = Math.floor(Math.random() * myList.length);
alert(myList[y]);
Here's a wider discussion on array literals vs. arrays created via the Array() constructor.

Related

Removing words from array using regex

I am creating a program that involves removing text from an array. If a letter is included in a word in the array, then that word will be removed. My first test was successful, a simple regular expression with a small array:
var regex = /z/;
var words = ["eggs", "zebras", "lampshade"];
for (i = 0; i < words.length; i++) {
let testResult = regex.test(words[i]);
if (!testResult) {
words.splice(i, 1);
}
}
console.log(words);
As expected, it returned [ 'zebras' ]. Because this was successful, I quickly scaled up using an npm package called "an-array-of-english-words". I ran my new script:
const masterWords = require("an-array-of-english-words");
var regex = /z/;
var words = masterWords;
for (i = 0; i < words.length; i++) {
let testResult = regex.test(words[i]);
if (!testResult) {
words.splice(i, 1);
}
}
console.log(words);
Every time I run it it ends up returning values that do not abide by the regular expression. For example, the code above returned ['aa', 'aahed', 'aahs', ...] as its first few values. Do I have to change my code to deal with a bigger array? Am I making a stupid mistake I didn't notice?
I think it may be due to the fact that you are splicing the array and looping it at the same time.
For ex. if the length of array is 5 and the current index is 2, after splicing the array, the item at the index 3 will be moved to the index 2, and will be skipped in the next iteration, since the next index will be 3.
So, you can create a clone of the words and change it, while iterating the original array.
#Joey , in official documentation if you see , try using it this way as a workaround . Also #Igor Moraru's answer explains why the issue might be happening.
console.log(words.filter(d => /z/.test(d)))

Picking random values from array and creating new array

I have an array, and need to pick three random values from that array. These will the be put in a new array and I will be able to see the new array on my website. I also have to make sure that no value gets picked twice.
This is what I have so far:
var student = ["Hans","Ole","Nils","Olav","Per","Knut","Line","Pia"];
var velg = student[Math.floor(Math.random() * student.length)];
I'm thinking I should add an id to my HTML, so the new array will show on my website, but I'm not sure about the rest.
First sort it randomly and then get first three:
student
.sort(function(){
return Math.random() - 0.5;
})
.slice(0,3)
Since Math.random() returns random value between 0 and 1, while sort expects values to be positive or negative to determine order we, we need to subtract 0.5 to make those negatives possible.
You could try something like this in a loop
var students = ["Hans","Ole","Nils","Olav","Per","Knut","Line","Pia"];
var randomStudents = [];
for(var i = 0; i < 3; i++) {
var velg = student[Math.floor(Math.random() * students.length)];
randomStudents.push(velg);
}
Note that this can add duplicate students to the array. You should check if student is already in the array and try again.
Keyword for that would be recursion.
https://www.codecademy.com/courses/javascript-lesson-205/0/1

Javascript: Arrays and For Loop Basics

I'm new to javascript and have been trying to teach myself the basics. I do have some experience with C++.
I came across this example in the source I'm using for studying and the for loop looks strange to me:
<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = document.cookie;
alert("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
Would someone mind explaining why there is a [0] and [1] near the end of these statements?
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
A clearer way to write this statement is this:
var parts = cookiearray[i].split('='),
name = parts[0],
value = parts[1];
That doesn't have anything to do with the for-loop itself. Split returns an array of tokens; the string is split up at the given delimiter. You're simply accessing the first and second tokens in this array.
String.split creates an array using the assigned delimiter (in this case '='). The [0] and [1] are selecting the first and second elements of the array respectively (Javascript array element indexes start at zero).
Those are used to access the items in the arrays that you create.
It's more clear what they do, and also better for performance, if you put the array in a variable and access that. That way you don't have to create two identical arrays:
var cookie = cookiearray[i].split('=');
var name = cookie[0];
var value = cookie[1];
The code is splitting each cookie pair key=value into key ([0]) and value ([1]).
A for loop is an iterator. You can sort of think of it like a counter, or stepping progression. If you want to do something x number of times, then a for loop is your best friend. The issue, when you are first learning, is figuring out how to use them effectively.
I'll give you a relevant and nonrelevant (simplified) example:
Nonrelevant:
// Increase the value of x and print the new value to the console 20 times.
var x = 6;
for(var i = 0; i < 20; i++) {
x++;
console.log("Value of x: " + x);
}
If you take a close look it's really rather logical. You define an iteration variable i, tell it when to stop (i < 20...so stop if i = 20), how to progress with each iteration (i++ or i + 1).
So the code will enter the loop when i = 0...it will add 1 to the value of x (x++), resulting in x = 7. It does the same for each iteration, so when i = 1, x (7) + 1 = 8, so on and so forth until i = 20, then the code breaks out of the loop and continues on it's merry little way. When it breaks we have just added 1 to x 20 times. Since x used to equal 6, it now equals 26.
Relevant:
// Given array of length 10, print each element to the console
for (var i = 0; i < cookiearray.length; i++){
console.log(cookiearray[i]);
}
So here the for loop is the same, it simply iterates until i equals the length (number of elements, in this case) of the array (so 10 times). When i = 0, our code prints the element of the array at cookiearray[0]...when i = 1 it prints cookiearray[1]...so on and so forth for the entirety of the array.
What may confuse you in the example is the split function. Split returns an array. So this line:
name = cookiearray[i].split('=')[0];
...actually means assign the first element of the new array created from splitting the cookiearray's element at position i.
Let's assume that cookiearray[0] = "Hello=World". When i = 0, our code splits the string "Hello=World" into a new array where the element at the 0 position is "Hello", it then assigns this to the local variable name. So name = "Hello".

Writing 1 through 125 in javascript

I'm trying to write some code so that when the user clicks a button, the page writes the numbers 1 through 125, while modifying some in between My first question is how do I write the conde so that the function writes these numbers. Here's the code I have so far.
<script>
function randomNumber() {
var num = Math.floor(Math.random() * 125);
for (var i = 0; i < 125; i++) {
document.write(num);
}
</script>
My second question is how do I modify each a few of the numbers to read, for example, ten instead of 10. I assume that this will use a nested for loop, unless I'm wrong. Any help would be great! Thank you.
your code is on the right track
<script>
function randomNumber() {
for (var i = 0; i < 125; i++) {
var num = Math.floor(Math.random() * 125);
console.log(num);
//document.write(num); - bad!
}
}
document.getElementById('yourElement').onclick = randomNumber;
</script>
You didn't close off your function, unless it was a mis-copy. Also, your variable num needs to be within the for loop so it can call a random number each tick, unless you want one random number written 125 times, then keep num outside randomNumber().
Secondly, don't use document.write, it is bad practice. Utilize document.getElementById('yourElement').innerHTML = num.
Lastly, if you want to resolve the number based upon it's english counterpart, you will need an object with numbers 1 - 125, and their respective word set as the value of each number...
var numbers = {
1: "one",
2: "two"
// etc....
}
In the loop you will need something along the lines of a switch or if/else if chain that has a condition for each number and utilizes your i increment as an index number[i] to print out the proper text.

Extract array values with last extraction memory on callback in javascript

Let's say I have a dynamic array that is populated on page load with various amounts of strings inside:
var arr = ["string1","string2","string3","string4","string5","string6","string7","string8","string9","string10","string11","string12","string13","string14","string15","string16","string17","string18"];
I then have a function that is called on each event (let's say a click) that needs to bring back 3 strings of the array consecutively while remembering which value it left off at, the last time it was called. So:
First time function is called, it returns:
string1, string2, string3
Second time it is called, it returns:
string4, string5, string6
and so on...
I don't the need the code for the click event or the callback function, rather the code for the function that would generate the extraction each time and bring it back. Something simple like being able to call:
arr.runExtraction();
on each callback and having it bring back the desired data.
What should happen if the array is exhausted? Start from the beginning?
You could do something like this:
function get_iterator(values, steps, start) {
steps = steps || 1;
var current = start || 0,
max = values.length;
return function() {
var end = current+steps,
end = end > max ? max : end,
t = values.slice(current, end);
current = end % max;
// or if you don't want to wrap around:
// current = end;
return t;
}
}
Edit: Added start parameter.
As current will be the same as values.length in the end, splice will return an empty array if you don't wrap around.
Using slice won't change the original array.
And then
var extract = get_iterator(arr, 3);
var arr1 = extract(); // gives you the first three elements
var arr2 = extract(); // gives you the next three elements etc.
DEMO
It might give you less elements in the "last" extraction if the number of elements is not divisible by number of extracted elements. The next call will let it start from the beginning again. You could also modify it that it wraps around and takes elements from the beginning so that it will always return as many elements as you have specified.
Reference: Array.prototype.slice
var arr = ["string1","string2","string3","string4","string5","string6","string7","string8","string9","string10","string11","string12","string13","string14","string15","string16","string17","string18"];
var runExtraction = function () {
return arr.splice(0, 3);
}

Categories