How to add dynamically growing array into another dynamic array - javascript

In my project i have arrays for date1, date2 and so on upto one month dates as shown below
var day1= [4,5,6,11];
var day2= [7,8,9,12];
var day3= [10,11,12,14];...
var day30= [1,2, 3, 4];
In the above each array exact size we dont know that may increase or decrease and i need to pass these values to the one more set of arrays like
var data1= [day1[0], day2[0], day3[0]];
var data2= [day1[1], day2[1], day3[1]];
var data3= [day1[2], day2[2], day3[2]];...
var data30= [day1[30], day2[30], day3[30]];
As per the day array size data array size will increase.
How to solve this issue any help..?

Consider using an object instead of variables:
var days = {
day1: [4,5,6,11],
day2: [7,8,9,12],
...
day30: [1,2, 3, 4]
};
Then you can do something like:
var data30 = [];
var i = 0;
while ( days.hasOwnProperty('day' + ++i) ){
data30.push(days['day' + i]);
}
Though given the sample data, data30 won't have any members because the first array has no member at index 30.

Check out JavaScript's push method.
http://www.w3schools.com/jsref/jsref_push.asp

Related

Reorganizing multidimensional arrays based on multiple value characteristics in JavaScript?

I'm having trouble organizing this data the way I would like it to. On my pages, a few things happen that I know work...
Some PHP spits out a multidimensional associative array. The top level of this array is an array of regions. Each region is an array of timezones.
Some more PHP creates a second multidimensional associative array. The top level of this array is an array of regions. Each region is an array of UTC offsets.
Both arrays are generated in the same order from the same data. This means that $offsets["region"][0] will have be based on the same timezone as $timezones["region"][0].
Both arrays are encoded into JSON and passed to my JavaScript.
I have the following JavaScript code...
var tempCurrentTimezoneArray = timezoneArray[ $("select[name='region_selector']").val() ];
var tempCurrentOffsetArray = timezoneOffsetArray[ $("select[name='region_selector']").val() ];
var groupedTimezones = {};
var groupedOffsets = {};
for (counter = 0; counter < tempCurrentOffsetArray.length; counter++) {
significantOffset = tempCurrentOffsetArray[counter].substr(tempCurrentOffsetArray[counter].length - 2);
if (!(significantOffset in groupedTimezones)) {
groupedTimezones[significantOffset] = [];
groupedOffsets[significantOffset] = [];
}
groupedTimezones[significantOffset].push(tempCurrentTimezoneArray[counter]);
groupedOffsets[significantOffset].push(tempCurrentOffsetArray[counter]);
}
var offsetArray = [];
for (var property in groupedTimezones) {
if (!groupedTimezones.hasOwnProperty(property)) {
continue;
}
groupedTimezones[property].sort();
groupedOffsets[property].sort();
offsetArray.push(parseInt(property));
}
offsetArray.sort();
var currentTimezoneArray = [];
var currentOffsetArray = [];
for (counter = 0; counter < offsetArray.length; counter++) {
currentTimezoneArray = currentTimezoneArray.concat(groupedTimezones[offsetArray[counter]]);
currentOffsetArray = currentOffsetArray.concat(groupedOffsets[offsetArray[counter]]);
}
In the top two lines I remove all of the timezone data not pertaining to the region selected on the page. This means that I am left with 2 single-dimensional arrays. Any given index of either array relates directly to the other array. I.E....
tempCurrentOffsetArray[0] is the UTC offset of the timezone found at tempCurrentTimezoneArray[0].
The rest of this code is intended to complete the following tasks...
Group timezones and offsets by their UTC offset.
Organize each offset group in alphabetical order.
Create two arrays where values are organized first by UTC offset and second by alphabetical order.
The problem I'm having is that on some regions I receive almost perfect listings,and on others I receive some listings with a seemingly random number of undefined values, and I'm not sure why. Can anyone identify the syntactical or logical errors in my code?
JSON of tempCurrentTimezoneArray input data here
JSON of tempCurrentOffsetArray input data here
You think still too complicated. It is a mess to keep these two Arrays in sync, better use one Array with objects.
var region_selector = $("select[name='region_selector']").val();
var tempCurrentTimezoneArray = timezoneArray[ region_selector ];
var tempCurrentOffsetArray = timezoneOffsetArray[ region_selector ];
//consolidate the Arrays
var data = []; //create a new Array `data`
for(var i = tempCurrentOffsetArray.length; i--; ){
//write into Array `data` at index `i` an object, containing these properties:
//`timezone`, `offset` and `offsetValue`, and their respective values
data[i] = {
timezone: tempCurrentTimezoneArray[i],
offset: tempCurrentOffsetArray[i],
//the + at the beginning converts the value behind that into a Number, like parseFloat() would do
offsetValue: +tempCurrentOffsetArray[i].match(/^GMT([+-]\d+(?:\.\d+)?)$/)[1]
}
}
//sorter-function for data to sort the values by offsetValue ASC first, then by timezone ASC
function sortedByOffset(a, b){
return a.offsetValue - b.offsetValue || a.timezone.localeCompare(b.timezone);
}
//you should do this as late as possible, usually after the filtering
data.sort(sortedByOffset);
If you insist on the two output-Arrays
var currentTimezoneArray = data.map(d => d.timezone);
var currentOffsetArray = data.map(d => d.offset);
otherwise this is imo more flexible
//utilities to fetch a property off the object
var getTimezone = d => d.timezone;
//aka function getTimezone(d){ return d.timezone }
var getOffset = d => d.offset;
//aka function getOffset(d){ return d.offset }
//example usages:
data.filter(d => d.offset === "GMT-5").map( getTimezone );
data.filter(d => d.offsetValue >= -2 && d.offsetValue <= -5 ).map( getOffset );
taking the first example; thinking in terms of a SQL-statement this would be
SELECT timezone FROM data WHERE offset = "GMT-5"
get me the timezone-values for each entry where the offset is GMT-5
you start with an Array containsing all values data then you get the subset you are interested in (in this case every entry, with the offset "GMT-5") by filtering.
Now you have an Array containing all values you are intersted in, but still the whole objects; like a SELECT * FROM ...
the map() function calls the function getTimezone() on every entry in this subset and returns another Array containing only the timezone-values.
The second example defines a range for the filter (every entry from GMT-2 to and including GMT-5 and every GMT in between) and returns for these entries the offset-protperty.
I discovered the issue with my code. There were actually three issues the first being on line 6. After looking over the data one more time I realized that some of the values had offsets that were floating point integers or had more than two significant digits. The new line 6 is...
significantOffset = tempCurrentOffsetArray[counter].replace(/[^\d.-]/g, '');
The second issue with my code also had to do with parsing floating integers. On line 21 we need to use parseFloat instead of parseInt. The new line 21 is...
offsetArray.push(parseFloat(property));
The third issue lies on line 23. sort() needs to be told how to sort the integers. This is the new line 23...
offsetArray.sort(function(a, b){return a-b});
The final code looks like this...
var tempCurrentTimezoneArray = timezoneArray[ $("select[name='region_selector']").val() ];
var tempCurrentOffsetArray = timezoneOffsetArray[ $("select[name='region_selector']").val() ];
var groupedTimezones = {};
var groupedOffsets = {};
for (counter = 0; counter < tempCurrentOffsetArray.length; counter++) {
significantOffset = tempCurrentOffsetArray[counter].replace(/[^\d.-]/g, '');
if (!(significantOffset in groupedTimezones)) {
groupedTimezones[significantOffset] = [];
groupedOffsets[significantOffset] = [];
}
groupedTimezones[significantOffset].push(tempCurrentTimezoneArray[counter]);
groupedOffsets[significantOffset].push(tempCurrentOffsetArray[counter]);
}
var offsetArray = [];
for (var property in groupedTimezones) {
if (!groupedTimezones.hasOwnProperty(property)) {
continue;
}
groupedTimezones[property].sort();
groupedOffsets[property].sort();
offsetArray.push(parseFloat(property));
}
offsetArray.sort(function(a, b){return a-b});
var currentTimezoneArray = [];
var currentOffsetArray = [];
for (counter = 0; counter < offsetArray.length; counter++) {
currentTimezoneArray = currentTimezoneArray.concat(groupedTimezones[offsetArray[counter]]);
currentOffsetArray = currentOffsetArray.concat(groupedOffsets[offsetArray[counter]]);
}

How to create multiple objects based on dynamic data?

Basically what i'm doing, is trying to create my own steam market JSON, by HTML parsing.
Example of how I'm currently doing that :
var url = 'http://steamcommunity.com/market/search?appid=730'
var itemDiv = $("<div></div>")
$.get(url).success(function(r){
data = $(r).find('stuff i need')
itemDiv.append(data)
})
and now say I wanted to find names of the items in the div, i would do something like :
itemDiv.find('x').each(function(){
var name = $(this).find("y").text()
// console.log(name) [or do whatever is needed ect]
})
As I mentioned before, I need to return objects based on that data in the format of:
var item = {name:"",price:0}
However, things like price will always be changing.
Based on the data thats in the div, the final product would look along the lines of :
var x = {name:"a",price:1}
var x2 = {name:"a2",price:2}
How do I go about doing this? I thought maybe i could store the data in an array, and then do something like
for(x in y){
return object
}
or something along those lines.
Sorry if this seems like a bonehead question, I'm pretty new to javascript.
clarification: i'm trying to figure out how to return multiple objects based on the data inside the div.
Here is the code that builds an array of objects based on two arrays (assuming they are of equal length).
function buildStocks() {
// Names and prices can also be passed as function arguments
var names = ['a', 'b', 'c'];
var prices = [1, 2, 3];
var result = []; // Array of these objects
for (var i = 0; i < names.length; i++) {
result.push({
name: names[i],
price: prices[i]
});
}
return result;
}

How to do math with an array (add +1)

I have a value in an input like this:
7*7*0*0*32*17
I do a simple .split('*') to obtain the following arrays:
["7","7","0","0","32","17"]
Then I transform the arrays into numbers with .map(Number), so the arrays are now composed not of strings but numbers:
[7,7,0,0,32,17]
What interests me is the second 7. I use a .slice(1,2) in order to select it alone. Until that point, it works:
[7]
My problem is, I can't add +1 to transform the 7 into a 8. Instead, it returns 71.
Let's call the array of ["7","7","0","0","32","17"] -> "myArray" to simplify the whole stuff.
console.log(myArray);
var myArrayMapped = myArray.map(Number);
console.log(myArrayMapped);
var myArraySliced = myArrayMapped.slice(1,2);
console.log(myArraySliced);
var myArrayIncreased = myArraySliced + 1;
console.log(myArrayIncreased);
And here will be the results of the console.logs:
["7","7","0","0","32","17"]
[7,7,0,0,32,17]
[7]
71
Everything works as expected up until this line, which doesn't work:
var myArrayIncreased = myArraySliced + 1;
Note that my final goal is to put back the 8 inside the input, and reconstruct the array into one single string like below, so maybe there's a simplier and faster solution I haven't seen. Basically, a button will call a function to add +1 to the very specific part of value I want to select (the second "7"):
From:
7*7*0*0*32*17
To:
7*8*0*0*32*17
Thanks in advance. Note that I do not want to sum up all the arrays, nor push a new array among the ones I got (which are the topics I've seen through my research, which don't help me). I just want to do maths with one specific array.
You are not adding one to 7, you are adding one to an array that has a single index.
var myArrayIncreased = myArraySliced + 1;
//var myArrayIncreased = [7] + 1;
If you want to do the addition, you need to use the first index
var myArrayIncreased = myArraySliced[0] + 1;
//var myArrayIncreased = 7 + 1;
Instead of using slice, you could select it with it's array index
myArrayMapped[1] += 1;
which would make the final code
var myArray = ["7","7","0","0","32","17"];
console.log(myArray);
var myArrayMapped = myArray.map(Number);
console.log(myArrayMapped);
myArrayMapped[1] += 1;
console.log(myArrayMapped);
You are adding [7] with 1
instead of 7 with 1
[7]+1 = '71'
After get your numeric array sliced and get [7], you should refer to the element's content which should look:
var myArrayIncreased = myArraySliced.map(function(n){return n+1});
console.log(myArrayIncreased);
Do:
var myArrayIncreased = 1*myArraySliced + 1;

Appending to an object in a list of objects

I have a javascript array that contains objects and looks like this:
[{‘sku':’ASD',’price': 10.99,’name':’Hot Sauce',’quantity': 1}, {‘sku':’JKL',’price': 8.99,’name':’Chilli Peppers',’quantity': 1}, {‘sku':’UIO',’price':’10.50',’name': "Sip 'n' Sizzle T-Shirt",’quantity': 1}]
I have a variable that contains the subtotal for the entire order and I would like to append it to each object for database purposes.
I tried this, but it messed everything up.:
var allProdData = prodData.push({total: total})
I assume I have to a use a for loop, but I'm not quite sure how to do it.
I had the same problem a couple of days ago try this
for(key in Objectname){
var allProdData = prodData.push(Objectname[key].total)
}
Put the correct objectname
First give a correct format for your array like below:
var arr = [{sku:'ASD',price: 10.99,name:'Hot Sauce',quantity: 1}, ...]
Then loop the array, calculate the total and format a new array
var arrNew = [];
for (var i = 0; i < arr.length; i++){
var total = arr[i].price * arr[i].quality;
arrNew.push({sku:arr[i].sku,price: arr[i].price,name:arr[i].name,quantity: arr[i].quality, total:total});
}

jquery get the unreapeatable values

i have a array with numbers. i need that array value to be generated once i click on the button, while i click on the button i need to get the value random wise from the array, but the value should not be repeated.
ex, if i get a 2 from out of 5, then i should not get the 2 again. for this i wrote this function, but the values are repeating... any idea?
var ar = [0,1,2,3,4,5];
var ran = Math.floor(Math.random()*ar.length);
ar.splice(ran,1);
alert(ar.splice);
the array values should not be removed. because if i click the button again, i need to get the values like before.
i did my work like this : but the rand values are repeating, any one can correct this to get unrepeatable values to get?
$(document).ready(function(){
var myArray = [1,2,3,4,5];
var mySize = 5;
x = 0;
while(mySize>=1){
var rand = Math.floor(Math.random()*mySize);
mySize--;
alert(rand);
}
})
You need your array to be in an outer scope for this like:
(function(){
var ar = [0,1,2,3,4,5];
document.getElementById('thebutton').onclick = function(){
alert(ar.splice(Math.floor(Math.random()*ar.length), 1));
};
})();
JSFiddle Example
If you create your array inside the onclick function then you are just recreating the entire array every time the button is clicked.
Take a look at this demo. In this it randomizes the array values and will repeat only after all the values are utilized.
Demo
Based on the update in your question here it is take a look.
http://jsfiddle.net/MbkwK/2/
var ar = [0, 1, 2, 3, 4, 5];
document.getElementById('thebutton').onclick = function() {
var shuffle = [];
var copyarr = ar.slice(0);
var arlength = copyarr.length;
for (i = 0; i < arlength; i++) {
shuffle.push(copyarr.splice(Math.floor(Math.random() * copyarr.length), 1));
}
alert(shuffle.join(","));
};
Working demo - http://jsfiddle.net/ipr101/qLSud/1/

Categories

Resources