iterating over an array while copying only integers to another in js - javascript

I have tried iterating over the array holder2 while copying it's integer elements to another array temp. But it doesn't seem to work as the content of temp remained the same.
var holder=getElementById("userinput").value;
var holder2=holder.split(" ");
var temp =[];
for(vari=0;i<holder2.length;i++){
if(isNaN(holder2[i])===false){
temp[i]=holder2[i];
}
}

That's not how you add an element to an array in Javascript. What you're looking for is push().
temp.push(holder2[i]);

You mentioned that you want integers only and that temp is empty. I'd suggest verifying that elements are integers and then using Array.push().
var holder=getElementById("userinput").value;
var holder2=holder.split(" ");
var temp =[];
for(var i=0;i<holder2.length;i++){
if(isNaN(holder2[i])===false && holder2[i] % 1 === 0){
temp.push(holder2[i]);
}
}

Try this:
var holder=getElementById("userinput").value;
var holder2=holder.split(" ");
var temp =[];
for(var i=0;i<holder2.length;i++){
var num = parseInt(holder2[i])
if(isNaN(num)===false){
temp.push(num)
}
}

Related

Create variables based on array

I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
MichaƂ

How to convert variable to two dimensional array using java script

I have a variable which contains data like this
var values = "VItDTotal,123,234,234,2345,1234,123,435,10,TestCase,123,234,234,2345,1234,123,435,5"
and I want to convert this string of data to a two dimensional array like this
[VItDTotal,123,234,234,2345,1234,123,435,10] //1st row
[TestCase, 123,234,234,2345,1234,123,435,5] //2nd row
How can I convert a JS variable to a two dimensional array?
I want to append these values to a datatable, how can I achieve this by using jQuery?
I hope this might help...
var values = "VItDTotal,123,234,234,2345,1234,123,435,10,TestCase,123,234,234,2345,1234,123,435,5"
var splittedArray = values.split(',')
var resultArray = new Array();
var resultKey = -1;
for(var i=0; i<splittedArray.length; i++) {
if(isNaN(splittedArray[i])) {
resultKey++;
resultArray[resultKey] = new Array();
resultArray[resultKey].push(splittedArray[i])
} else {
resultArray[resultKey].push(splittedArray[i])
}
}
I work this way:
//get the index where ",TestCase" is
var index = values.indexOf(",TestCase");
//create two arrays to the values
var part_one = [], part_two = [];
//slice the value from 0 to index and push part one
part_one.push(values.slice(0,index));
//slice the value from index+1 to the end and push part two
part_two.push(values.slice(index+1, values.length));
Not my favourite, but, are you after something like this?
var values = ["VItDTotal",123,234,234,2345,1234,123,435,10,"TestCase",123,234,234,2345,1234,123,435,5];
var vals = [values.
join(",").
replace(/,([a-z]+)(?!.*[a-z]+)/gi, " devider $1").
split(/\s+devider\s+/gi)];
console.log(vals);

Javascript Getting value from exact field from associative array

I have an associative array - indexed by dates. Every element holds another array.
[03/16/2015: Array[3], 03/17/2015: Array[3], 03/18/2015: Array[3], 03/19/2015: Array[3]]
I created it with this code:
array[cellDate][i]=cellText;
How can I get the value for example from cell 03/16/2015 array[2] ??
var text=array['03/16/2015'][2];
With this line of code I got an error.
EDIT:
http://www.traineffective.com/schedule/
I store in that array title of blocks dropped in the schedule (title of block of 'empty' value if cell is empty)
What I want to achive is remeber the order of the blocks for particular weeks , and when user changes week with arrows it loads block based on date withdrowed from array.
Code where I create array :
function saveWeekToArray(array){
var cellDate;
var cellText;
var tmpText;
var i;
workoutsTD.each(function(){
cellDate=$(this).attr("data-day");
array[cellDate]=['','',''];
i=0;
$(this).children('.workout-cell').each(function(){
if (!$(this).hasClass('workout-cell-empty')){
cellText=$(this).find('span').text();
array[cellDate][i]=cellText;
} else {
array[cellDate][i]='empty';
}
i++
});
});
}
Code where I load data from array (One with the error )
function loadBlocksFromArray(array){
var cellDate;
var cellText;
var tmpText;
var i;
workoutsTD.each(function(){
cellDate=$(this).attr("data-day");
i=0;
$(this).children('.workout-cell').each(function(){
if ((array[cellDate][i])!='empty'){
cellText=array[cellDate][i];
$(this).append(createBlock(cellText));
$(this).removeClass('workout-cell-empty');
}
i++;
});
});
}
When you will click sumbit button in console log you will see the structure of array.
I got error while changing the week its :
enter code hereUncaught TypeError: Cannot read property '0' of undefined
In Javascript, there is no concept of an associative array. You either have arrays (which are indexed by numbers) or you have Objects (whose elements are indexed by strings).
What you instead want is an object containing all of your arrays. For example:
var data = {
'3/4/2015' : ['val1', 'val2', 'val3'],
'3/8/2015' : ['val1', 'val2', 'val3']
};
Then you can access your elements in the way that you want:
var ele = data['3/4/2015'][1];
https://jsfiddle.net/x9dnwgwc/
That is the effect what I wanted achive. Thanks for hint Harvtronix!
var jsonObj = { workout : {} }
var i;
var k;
var workoutArray = [];
for(i=1; i<=7; i++){
var newWorkout = i+ "/12/2015";
for (k=0; k<=2; k++){
var newValue = "workoutTitle" + k;
workoutArray[k]=newValue;
}
jsonObj.workout[newWorkout]=workoutArray;
}
console.log(jsonObj);
for(i=1; i<=7; i++){
var newWorkout = i+ "/12/2015";
var tmpArray= jsonObj.workout[newWorkout];
console.log(tmpArray);
}

How to sort an array based on values of another array?

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);

attempting to convert String data into numerical data, the drop the data into an array of arrays (Json)

I have this:
(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)
I'm attempting to get the output to look like this:
"coords": [[65.94647177615738, 87.890625],[47.040182144806664, 90],[45.089035564831036, 122.34375]]
Any Idea?
The first result comes back to me as a string, so when i try to assign the first object to an array, the console shows me this:
array is: "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)"
var str = "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)";
str = str.slice(1,-1); // remove outermost parentheses
var arrCoord = str.split(')(');
for (var i=0; i<arrCoord.length; i++) {
var tarr = arrCoord[i].split(", ");
for (var j=0; j<tarr.length; j++) {
tarr[j] = parseFloat(tarr[j]);
}
arrCoord[i] = tarr;
}
// arrCoord is now populated with arrays of numbers
Decided to sort of play code golf. Assuming:
var sample = '(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)';
Then:
var coords = sample
.split(/\(([^)]+)\)/)
.filter(function(v){return v!=""})
.map(function(v){return v.split(/[^0-9\.]+/)})

Categories

Resources