I have below String that needs to be divided into multiple array after 5 comma separated values. Then I need to put each array values to textbox values using script. I tried the below code to split and assign to array but not working. Is there any way this can be resolved? <%=ab%> is the JavaScript variable that contains the below code.
[768.234.232, 768.234.232, 574,10-10-2012, 10-10-2012, 768.234.232, 768.234.232, 987, 10-10-2012, 10-10-2012]
function functionOne() {
var list = "<%=ab%>";
var ab = new Array();
var i = 0;
for (i = 0; i < 10; i++) {
ab[i] = list.split(",", 3);
alert(ab[i]);
}
}
"needs to be divided into multiple array after 5 comma seperated values"
You seem to be saying that the result should be one array with five values in it and then a second array with the next five values in it, etc. If so, you can do the following:
var list = "<%=ab%>";
list = list.slice(1,-1); // remove the enclosing []
var allValues = list.split(/\s*,\s*/); // split on comma with optional whitespace
var a = [];
for (var i = 0; i < allValues.length; i+=5) {
a.push( allValues.slice(i, i+5<=allValues.length ? i+5 : allValues.length) );
}
After running the above, a will be array that contains other arrays. a[0] is an array of the first five items, so, e.g., a[0][2] is the third item. a[1] is an array of the next five items. If there were more than ten items in the original list then a[2] would be an array of the next five, etc. If the total number of items is not divisible by five then the last array would hold the remainder.
Demo: http://jsfiddle.net/9xAxz/
"Then I need to put each array values to textbox values"
Um... does that mean one item per textbox? If so, why did you want to divide up after five values? Do you mean five items per textbox? Either way are you talking about dynamically creating textboxes? If so you can follow the above code with something like this:
var tb;
for (i = 0; i < a.length; i++) {
tb = document.createElement('input');
tb.value = a[i].join(", ");
document.body.appendChild(tb);
}
Demo: http://jsfiddle.net/9xAxz/1/
If I'm completely off base on any of the above, well... think about editing your question to make it clearer. I suppose I should've clarified before answering, but please update the question to show what your desired output is for that input.
function functionOne() {
var list = "<%=ab%>".split(/,\s?/g);
for (var i = 0; i < list.length; i++) {
t = document.createElement('input');
t.type = 'text';
t.value = list[i];
document.body.appendChild(t);
}
}
functionOne();
http://jsfiddle.net/WJPHt/1/
Related
I can't seem to assign an array value to a variable. It always returns undefined.
In my code I have set currentWord = text[wordPos]. At the end of the code I have console logged currentWord, and text[wordPos]. My thinking says that they should return the same value, but they don't. currentWord returns undefined, and text[wordPos] returns the correct value (the first word in the 'text' array).
Solved. I had mistakenly forgot that I had 2 arrays, and thought the text array was not empty, but it was. The words array is the array I had filled in separate file.
var text = Array();
var wordPos = 0;
var currentWord = text[wordPos];
function gen() {
text = [];
var random;
for (var i = 0; i < 10; i++) {
random = words[Math.floor(Math.random() * 50)];
text.push(random);
}
document.getElementById('text').innerHTML = text.join(" ");
console.log(currentWord);
console.log(text[wordPos]);
}
Currentwork is undefined because you create an array object but never push a value into it. It transfers the current value of the variable not the reference.
There is no value at index 0 of text. If you assign some values to the text array you should be good!
Updated:
Read the OP's note above about the two arrays in the original example. In light of this information, the following script simulates an imported array words of 50 distinct values in order to generate a text of ten space-delimited numbers and indicate its first value:
// simulating an array imported from a separate file
var words = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50];
function gen() {
var wordPos = 0;
var currentWord = "";
var arr = [];
var randomVal;
var d = document;
d.g = d.getElementById;
var pText = d.g('text');
// get each of 10 values by randomly selecting an element's key
for (var i = 0; i < 10; i++) {
randomVal = words[ Math.floor( Math.random() * 50 ) ];
arr.push( randomVal );
}
pText.innerHTML = arr.join(" ");
currentWord = arr[wordPos];
console.log("Current word: ",currentWord );
}
gen();
<p id="text"></p>
This script randomly selects 10 numbers and adds them to an empty array by means of variable randomVal. This variable acquires a value in each iteration of the for-loop, during which the variable is passed to the push() method of arr in order to append it to the array. Once the loop terminates, the script joins the elements of arr on a blank space character, which yields a string whose numeric values are space-delimited.
One can discern that the script is working correctly when the console.log statement displays the first numeric value appearing in the text.
So what I have is a quiz which is generated dynamically. I want the quiz questions to be ordered randomly. Basically, the i is going from 0 to the length of answerArray. I want it to do this, but not in order randomly. For instance: instead of 0,1,2,3,4,5 I want 1,0,2,3,5,4. I have tried doing this but all of my attempts failed. It would be very helpful if I could do this so the test questions would not always be in order. Thank you.
var displayAnswers = function (){
for (var i = 0; i<answerArray.length;i++){
var row1= document.createElement("div");
$(row1).addClass("row");
var colmd= document.createElement("div");
$(colmd).addClass("row");
$(colmd).addClass("text-center");
$(colmd).addClass("rowtxt");
$(colmd).attr('id',"questionTxt"+[i+1]);
$("#contain").append(row1)
$(row1).append(colmd);
var answer = answerArray[i];
}
You can use accepted answer in the following question Generate unique random numbers between 1 and 100, that will generate the random numbers first and store them in array and use them inside for loop.
Example :
var arr = [];
var answerArray = ["Answer 1", "Answer 2", "Answer 3"];
while( arr.length < answerArray.length ){
var randomnumber=Math.ceil( Math.random() * answerArray.length)
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==randomnumber){found=true;break}
}
if(!found)arr[arr.length]=randomnumber;
}
Now you have an array of unique numbers between 0 and answerArray length, you can use it inside the loop just by calling arr[i] :
var displayAnswers = function (){
for (var i = 0; i<answerArray.length;i++){
var row1= document.createElement("div");
$(row1).addClass("row");
var colmd= document.createElement("div");
$(colmd).addClass("row");
$(colmd).addClass("text-center");
$(colmd).addClass("rowtxt");
$(colmd).attr('id',"questionTxt"+[i+1]);
$("#contain").append(row1)
$(row1).append(colmd);
//Here you get the unique number between 0 and answers length
var random_number = arr[i];
var answer = answerArray[random_number];
}
}
Hope this helps.
I would start by thinking about what you need to do.
You want to track what numbers you have used already and getting a new number if you have already used the one generated.
Try something like this.
// The initial array
var Array = [1,2,3,4,5];
// The new array or tracking array
var Used = [];
// A function to generate the random index
// We need a function so we can call it if
// the index already exists to ensure we have
// the same amount of values as the inital
// array
function addRandomNum(array) {
var random = Math.floor((Math.random() * Array.length) + 1);
if(array.indexOf(random) === -1){
array.push(random);
} else {
addRandomNum(array);
}
};
// Loop the inital array calling the function
for(var i = 0; i < Array.length; i++){
addRandomNum(Used);
}
// Look at the new randomized array
console.log(Used);
You could shuffle the array, if that is what you want.
There are shuffle functions if you follow this link of css-tricks:
https://css-tricks.com/snippets/javascript/shuffle-array/
I like technique 2. Which uses the sort function to randomly create a negative or positive number which will sort the items according to the returned value.
If the returned value is positive, the first item will precede the second that is passed to the function. As you can see, the parameters are unused because we don't want a logic sort but a randomized based on a random number.
You could call it like this:
answerArray.sort(function(item1, item2) { return 0.5 - Math.random() });
Ok, I will assume a few things. Your answerArray looks like this:
var answerArray = [
{
"q_id": "1",
"prompt": "Is StackOverflow awesome?",
"a1": "Yes",
"a2": "No",
"correct": "a1"
}
];
First add a property like this
"random": Math.floor(Math.random() * 101)
This will create a random number that you can use to sort the array, like so:
answerArray.sort(function(a, b) {
return parseFloat(a.random) - parseFloat(b.random);
});
This way you can sort the questions randomly.
I have an array that has following values
Nata_sha_AD8_02_ABA
Jack_DD2_03_K
Alex_AD8_01_PO
Mary_CD3_03_DC
John_DD2_01_ER
Daniel_AD8_04_WS
I want to group them based on following array ['AD8','CD3','DD2','PD0']; and sort each group based on number of each value. So the output should be
Alex_AD8_01_PO
Nata_sha_AD8_02_ABA
Daniel_AD8_04_WS
Mary_CD3_03_DC
John_DD2_01_ER
Jack_DD2_03_K
So far, I wrote following code, but it does not work properly, and I am stuck here.
var temparr = [];
var order = 1000;
var pos = -1;
var temp = -1;
var filterArray= ['AD8','CD3','DD2','PD0'];
for (i =0; i< filterArray.length; i++) {
for (j =0; j < myarray.length; j++) {
if(filterArray[i].toUpperCase().search(myarray[j])>0){
temp = str.substring(myarray[j].indexOf(filterArray[i])+4, myarray[j].indexOf(filterArray[i]+6);
if(temp < order){
pos = j;
order = temp;
}
if(j == myarray.length-1){ //reached end of the loop
temparr.push(myarray[pos]);
order = 1000;
}
}
}
}
Using the first sort parameter you can pass a function to run to sort the array. This function receives 2 values of the array, and should compare them and return less than 0 if the first is lower than the second, higher than 0 if it is higher, or 0 if they are the same. In my proposition, I split the name and "token" part of the values, and then compare the tokens to order them correctly. Using the indexOf on the filterArray allows me to compare the position of the tags accordingly.
var array_to_sort = ['Natasha_AD8_02',
'Jack_DD2_03',
'Alex_AD8_01',
'Mary_CD3_03',
'John_DD2_01',
'Daniel_AD8_04'
];
var filterArray = ['AD8', 'CD3', 'DD2', 'PD0'];
array_to_sort.sort(function(a, b) {
a_token = a.substr(a.indexOf('_')+1); //Remove the name part as it is useless
b_token = b.substr(b.indexOf('_')+1);//Remove the name part as it is useless
if(a_token.substr(0,3) == b_token.substr(0,3)){//If the code is the same, order by the following numbers
if(a_token > b_token){return 1;}
if(a_token < b_token){return -1;}
return 0;
}else{ //Compare the position in the filterArray of each code.
if(filterArray.indexOf(a_token.substr(0,3)) > filterArray.indexOf(b_token.substr(0,3))){return 1;}
if(filterArray.indexOf(a_token.substr(0,3)) < filterArray.indexOf(b_token.substr(0,3))){return -1;}
return 0;
}
});
document.write(array_to_sort);
EDIT: This method will sort in a way that the filterArray can be in any order, and dictates the order wanted. After updates from OP this may not be the requirement... EDIT2: the question being modified more and more, this solution will not work.
My solution.
The only restriction this solution has has is that your sort array has to be sorted already. The XXn_nn part can be anywhere in the string, but it assumes the nn part always follows the XXn part (like DD3_17).
var result=new Array();
var p,x;
//loop the 'search' array
for(var si=0,sl=sort.length;si<sl;si++){
//create new tmp array
var tmp=new Array();
//loop the data array
for(var ai=0,al=arr.length;ai<al;ai++){
var el=arr[ai];
//test if element still exists
if(typeof el=='undefined' || el=='')continue;
//test if element has 'XXn_nn' part
if(arr[ai].indexOf(sort[si]) > -1){
//we don't now where the 'XXn_nn' part is, so we split on '_' and look for it
x=el.split('_');
p=x.indexOf(sort[si]);
//add element to tmp array on position nn
tmp[parseInt(x[p+1])]=el;
//remove element from ariginal array, making sure we don't check it again
arr.splice(ai,1);ai--;
}
}
//remove empty's from tmp array
tmp=tmp.filter(function(n){return n!=undefined});
//add to result array
result=result.concat(tmp);
}
And a working fiddle
On the basis that the filtering array is in alphabetical order, and that every string has a substring in the format _XXN_NN_ that you actually want to sort on, it should be sufficient simply to sort based on extracting that substring, without reference to filterArray:
var names = ['Nata_sha_AD8_02_ABA', 'Jack_DD2_03_K', 'Alex_AD8_01_PO', 'Mary_CD3_03_DC', 'John_DD2_01_ER', 'Daniel_AD8_04_WS'];
names.sort(function(a, b) {
var re = /_((AD8|CD3|DD2|PD0)_\d\d)_/;
a = a.match(re)[1];
b = b.match(re)[1];
return a.localeCompare(b);
});
alert(names);
I am trying to write some JavaScript that will select some random numbers from an array and then add those selected numbers to make a single total value.
For example if i had var array = [1, 22, 5, 88, 3, 105, 7, 88, 987] i would then like the code to select however many numbers it wants at random(amount selected changes every time it runs) and then add them together but i am not sure if this is even possible.
I am new to JavaScript so i have only managed to write code that adds all the array elements together instead of selecting at random.
var arr = [1,2,3,4,5,6];
var total=0;
for(var i in arr) { total += arr[i]; }
My code is very basic so please excuse me for this i'm still learning. Thank You
You could use the Math.rand() function in order to create a random index. In terms of code:
// The array with your elements
var arr = [1,2,3,4,5,6];
// An array that will keep track of the elements we have selected.
var selectedIndex = [];
// The sum.
var sum=0;
// times is the number of elements we want to select from arr and sum them.
for(var i=0; i<times; i++)
{
// Get a random integer number in the range [0, arr.length]
var index = Math.floor(Math.rand()*arr.length);
// check if the index we created has been selected again.
if(selectedIndex.indexOf(index)>-1)
{
// The created index has been selected again. So we must select another one,
// in order we get an item from the array only once.
while(selectedIndex.indexOf(index)>-1)
index = Math.floor(Math.rand()*arr.length);
}
// We push the created index in the selected index array.
selectedIndex.push(index);
// We increase the sum.
sum+=arr[index];
}
update
In order the above to be executed the caller should provide a value for the variable called times. This value in order to be valid shouldn't exceed the length of the array called arr.
Another way more elegant, it would be to follow on this part the solution that deitch suggested in his post.
var times = Math.floor((Math.random() * arr.length)+1)
The above should be placed just before the for statement.
I think you are looking something like:
<code>
function randormTotal() {
var arr = [1,2,3,4,5,6];
var total=0;
var noOfData = 3;
for(var i =0; i<noOfData; i++) {
var pos = Math.floor(Math.random()*(arr.length-1)) + 1;
total += arr[pos];
}
alert(total);
}
</code>
FYI, this method actually modifies the array, so you might want to copy it.
// randomly select how many elements you will pick
var i, total = 0, elmsCount = Math.floor((Math.random() * arr.length)+1), current;
// select that many elements
for (i=0; i<elmsCount; i++) {
current = Math.floor(Math.random()*arr.length);
total += arr.splice(current,1)[0];
}
// total is now the sum
Is there a way to create a dynamic array of strings on Javascript?
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Code is appreciated.
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Ok, so you need some user input first? There's a couple of methods of how to do that.
First is the prompt() function which displays a popup asking the user for some input.
Pros: easy. Cons: ugly, can't go back to edit easily.
Second is using html <input type="text"> fields.
Pros: can be styled, user can easily review and edit. Cons: a bit more coding needed.
For the prompt method, collecting your strings is a doddle:
var input = []; // initialise an empty array
var temp = '';
do {
temp = prompt("Enter a number. Press cancel or leave empty to finish.");
if (temp === "" || temp === null) {
break;
} else {
input.push(temp); // the array will dynamically grow
}
} while (1);
(Yeah it's not the prettiest loop, but it's late and I'm tired....)
The other method requires a bit more effort.
Put a single input field on the page.
Add an onfocus handler to it.
Check if there is another input element after this one, and if there is, check if it's empty.
If there is, don't do anything.
Otherwise, create a new input, put it after this one and apply the same handler to the new input.
When the user clicks OK, loop through all the <input>s on the page and store them into an array.
eg:
// if you put your dynamic text fields in a container it'll be easier to get them
var inputs = document.getElementById('inputArea').getElementsByTagName('input');
var input = [];
for (var i = 0, l = inputs.length; i < l; ++i) {
if (inputs[i].value.length) {
input.push(inputs[i].value);
}
}
After that, regardless of your method of collecting the input, you can print the numbers back on screen in a number of ways. A simple way would be like this:
var div = document.createElement('div');
for (var i = 0, l = input.length; i < l; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
I've put this together so you can see it work at jsbin
Prompt method: http://jsbin.com/amefu
Inputs method: http://jsbin.com/iyoge
var junk=new Array();
junk.push('This is a string.');
Et cetera.
As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9,10,11
var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9
You can even add elements like
var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30
you can even change the values
myArray[2] = 40
Printing Order
If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.
Page Submission
If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.
You can go with inserting data push, this is going to be doing in order
var arr = Array();
function arrAdd(value){
arr.push(value);
}
Here is an example. You enter a number (or whatever) in the textbox and press "add" to put it in the array. Then you press "show" to show the array items as elements.
<script type="text/javascript">
var arr = [];
function add() {
var inp = document.getElementById('num');
arr.push(inp.value);
inp.value = '';
}
function show() {
var html = '';
for (var i=0; i<arr.length; i++) {
html += '<div>' + arr[i] + '</div>';
}
var con = document.getElementById('container');
con.innerHTML = html;
}
</script>
<input type="text" id="num" />
<input type="button" onclick="add();" value="add" />
<br />
<input type="button" onclick="show();" value="show" />
<div id="container"></div>
The following code creates an Array object called myCars:
var myCars=new Array();
There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).
1:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
You could also pass an integer argument to control the array's size:
var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2:
var myCars=new Array("Saab","Volvo","BMW");
Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.
Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
document.write(myCars[0]);
will result in the following output:
Saab
Modify Values in an Array
To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel
Please check http://jsfiddle.net/GEBrW/ for live test.
You can use similar method for dynamic arrays creation.
var i = 0;
var a = new Array();
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
The result:
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8
Just initialize an array and push the element on the array.
It will automatic scale the array.
var a = [ ];
a.push('Some string'); console.log(a); // ['Some string']
a.push('another string'); console.log(a); // ['Some string', 'another string']
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']