I've been trying to create an array from a for loop, using push which creates an array in the format ["value, value, value, value, value, value"] but I need it to create an array in the following format: [["value, value, value"],["value, value, value"]
The original array is created without a for loop like this:
new array (["1","2",3"],["1,2,3"],["1,2,3"],["1,2,3"]);
so how do I go about creating the same using a loop instead?
var colour = ["red","green","blue","orange"];
for (i=1; i<5; i++){
var name = $("#name"+i).val();
var can = $("#candidate"+i).val();
arrayOfData = new Array([can,name,colour[i]]);
}
Just push your arrayOfData itself to an array.
var array = [];
var colour = ["red","green","blue","orange"];
for (i=1; i<5; i++){
var name = $("#name"+i).val();
var can = $("#candidate"+i).val();
arrayOfData = [can,name,colour[i-1]];
array.push(arrayOfData);
}
Demo here: http://jsfiddle.net/f5J5z/4/
Related
I have Json Parse list which need to push each category list.
example :
listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = [];
var values = [];
for(var i=0;i<listChartPeriods.length;i++){
categoryData.push(listChartPeriods.slice(0,1)[0]); //here need to push each date
values.push(listChartPeriods[i])
}
expected out put:
categoryData=["2018-05-04","2018-05-11","2018-05-18","2018-05-25","2018-06-01"]
values=[21807210.5028442,21807210.5028442,21807210.5028442]//each category values
Just use Object.keys to get the dates in the array.
const listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = Object.keys(listChartPeriods);
console.log(categoryData);
Below should get the job done for you. A for in loop is your friend when it comes to working with objects.
var listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = [];
for(var char in listChartPeriods){
for(var i = 0; i < listChartPeriods[char].length; i++){
categoryData.push(listChartPeriods[char][i]);
}
}
console.log(categoryData);
EDIT: Just read your updated question and you are only wanting the key names. You can also do this with a for in loop.
for(var char in listChartPeriods){
categoryData.push(char)
}
console.log(categoryData);
Following the solution:
for (let date in listChartPeriods){
categoryData.push(date);
let [first] = listChartPeriods[date];
values.push(first);
}
categoryData = ["2018-05-04", "2018-05-11", "2018-05-18", "2018-05-25", "2018-06-01"]
values = [21807210.5028442, 21807210.5028442, 21807210.5028442, 21807210.5028442, 21807210.5028442]
I am looking to grab a string value from a text box and multiple values from a multiselect list and associate them where the string value is the key, and the multiple values from the drop down list are the values.
Here is the javascript code I have thus far:
var serviceName = document.getElementById('servicePackageText').value;
var sourceType = document.getElementById("multiple-checkboxes");
var groupName = serviceGroupName;
var serviceArray = new Array();
for (i = 0; i < sourceType.selectedOptions.length; i++) {
serviceArray.push(parseInt(sourceType.selectedOptions[i].value));
}
I want the format to look like this:
"Textbox value": [
multiselect_values,
multiselect_values,
multiselect_values,
multiselect_values
]
Any tips on how to proceed?
You need wrapper object, then it is easy. All you have to do is use [] property accessor to assign the object property.
I took some liberty with your code to make it simpler to rationalize:
var serviceName = "myDog"; //mock document.getElementById('servicePackageText').value;
var sourceType = [1, 2, 3, 4]; //mock document.getElementById("multiple-checkboxes");
var groupName = {};
groupName[serviceName] = sourceType; // <--- THE ANSWER
console.log(groupName);
I mostly develop in Java, but I presently need to do some work using JavaScript.
I have data that I need to group by two dimensions: first by gender, and then by language. The object to be grouped comes like so:
var items =[ {
"language":"english",
"gender":"male",
...//twelve other fields
},
...
]
This is what I've tried:
var myMap = {};
for(var i=0; i<items.length;i++){
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myMap[_gender][_lang].push[item];
}
I assumed the above would work, but it’s not working. It keeps returning this error:
Uncaught TypeError: Cannot read property 'undefined' of undefined
Note: In Java, I would be creating a map of arrays.
One problem:
When you call myMap[_gender][_lang].push[item];, what you are actually doing is adding a key to the Object myMap, with the current value of _gender, and turning it into an Object, which you then create a new key for, set to the value of _lang. In addition, .push() is a function used with arrays, to add a new item onto the end of the array. If you want to add a new key and value to an Object, all you have to do is just call that key and assign it a value. Here's an example.
var obj = {
ex1 : 'example 1',
ex2 : 'example 2'
};
console.log(obj);
obj.ex3 = 'example 3';
console.log(obj);
//The code below will simply log 'undefined' in most consoles(it doesn't happen to do so in this snippet).
console.log(obj.ex4);
Here's my suggestion(assuming I correctly understand what you're trying to do):
var items = [{
"language":"english",
"gender":"male",
},
//...more below
];
myMap = [];
for(var i = 0; i < items.length; i++){
myArray = [];
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.push(myArray);
}
You are doing totally wrong. First of all myMap is object not an array so you can not use myMap.push().
You can achieve like this.
var items = {
"language":"english",
"gender":"male"
}
var myMap = {};
for(var key in items){
var myArray = [];
var _gender = items["gender"];
var _lang = items["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.item = myArray;
console.log(myMap);
}
for add 2-d array read this. 2-D Array in javascript
I have to iterate through an array, change one of its values, and create another array refelecting the changes.
this is what I have so far:
JS:
var arr = new Array();
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
arr['t2'] = i;
last.push(arr);
}
console.log(last);
Unfortunately, these are my results
As you can see, I am not getting the results needed as 0,1,2.. instead I am getting 2, 2, 2..
This is what i would like my results to be:
How can I fix this?
You have to make a copy, otherwise you are dealing with reference to the same object all the time. As it was said before - javascript does not have associate arrays, only objects with properties.
var arr = {}; // empty object
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
var copy = JSON.parse(JSON.stringify(arr)); //create a copy, one of the ways
copy['t2'] = i; // set value of its element
last.push(copy); // push copy into last
}
console.log(last);
ps: you can use dot notation arr.t1 instead of arr['t1']
The array access with ['t2'] is not the problem. This is a regular JavaScript feature.
The problem is: You are adding the SAME array to "last" (5 times in code, 3 times in the screenshot).
Every time you set ['t2'] = i, you will change the values in "last" also, because they are actually just references to the same array-instance.
You must create a copy/clone of the array before you add it to "last".
This is what will happen in all languages where arrays are references to objects (Java, C#...). It would work with C++ STL though.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx