I initialize my array as myArray=[]; I want to dynamically create an associative array in a for loop. I am trying to create a key index and push a new value in at the same time. I want each key index to be a number
like '1': '2': '3':
The number of indexes will be unknown so I need to create them in my loop
I am not sure how to accomplish this or push more values into each index. My code is:
var myArray=[];
for(i=0; i<10; i++){
myArray['1'].push(i);
myArray['2'].push(i);
myArray['3'].push(i);
}
alert(myArray);
There is an error in the code . I apologize if this is similar to a repeat question. I can not find this answer in my searches though. Thanks for any help.
You must initialize the subarrays in order to push. Better start with the index 0, tough.
var myArray = [[], [], []];
for(var i=0; i<10; i++){
myArray[0].push(i);
myArray[1].push(i);
myArray[2].push(i);
}
JavaScript arrays should be used with numeric indexes. If you want a map from string-valued keys to values, use a simple object:
var myMap = {};
To populate the map, you'll have to initialize the arrays for each key:
var myMap = { '1': [], '2': [], '3': [] };
Then your loop will work as-is.
edit — I may have misinterpreted your question. If you want your outer array to use just numeric indexes (I saw the strings and generalized, perhaps inappropriately) then you can indeed use an array of arrays:
var myMap = [ null, [], [], [] ];
(The first null is for index 0, which is implicitly where JavaScript array indexes start.)
Several things are wrong here:
#1
You want myArray to be an associative array, so as an object, it would be defined like so:
myArray = {};
#2
You cannot push() data in an array that has not been declared. Declare those arrays first:
myArray['1'] = [];
myArray['2'] = [];
myArray['3'] = [];
#3
You cannot directly alert() an array or an object. You need to get a string representation of it:
alert( JSON.stringify(myArray,null,4) ); // null,4 provides easy to read formating
JS Fiddle Demo
Related
Yes I know how to loop through arrays (types) in Javascript. The fact is, I'd like to know how to set a multiDimensionalArray array's value by a set of given indexes to keep it as generic as possible. For example I've an array with a length of 3 (which could as well be a length of 4, 100, ...):
var indexes = [0, "title", "value"];
I know the multidimensional array (mArray) can be set by putting the indexes like so:
multiDimensionalArray[0]["title"]["value"] = "Jeroen"; or multiDimensionalArray[indexes[0]][indexes[1]][indexes[2]] = "Jeroen";
The fact that the given indexes array can vary and does not always contain the same index names so I'm search for a solution like this:
multiDimensionalArray[indexes] = "Jeroen";
I don't know how to code the assignation if this. I've searched on Google/Stack Overflow. Maybe I'm using the wrong keywords. Can anyone help me?
Thanks!
Following example is how I've made it working thanks to Jonas's example:
var json = [{
"hello": {
"world": 1,
"world2": 2
},
"bye": {
"world": 1,
"world2": 2
}
}];
var indexes = [0, "hello", "world2"];
var value = "value";
indexes.slice(0,-1).reduce((obj, index) => obj[index], json)[indexes.pop()] = value;
console.log(json);
So imagine you have a structure like this:
var array=[[["before"]]];
Then you want
var indexes=[0,0,0];
var value="value";
to actually do:
array[0][0][0]="value";
which can be easily achieved with reduce:
indexes.slice(0,-1).reduce((obj,index)=>obj[index],array)[indexes.pop()]=value;
Explanation:
indexes.slice(0,-1) //take all except the last keys and
.reduce((obj,index)=>obj[index] //reduce them to the resulting inner object e.g. [0,0] => ["before"]
,array) //start the reduction with our main array
[indexes.pop()]=value;// set the reduced array key to the value
var array=[[[0]]];
var indexes=[0,0,0];
var value="value";
indexes.slice(0,-1).reduce((obj,index)=>obj[index],array)[indexes.pop()]=value;
console.log(array);
I have an array like below in java-script
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
]
I tried accessing the individual values and was able to by the below code
alert(Result[0].ID) or alert(Result[0].Phase)
Is there a way to access this by index? like Result[0][1], i tried but getting [object][object]
also i need to access column count
Please help me
You have array of object and by using for loop you can easily access all element value.
try following
function getValue() {
var keys ;
var Result = [{"ID":1,"Type":"Pyramid","Phase":"One"}, {"ID":2,"Type":"Pyramid","Phase":"Two"}]
for(var i=0; i<Result.length;i++){
keys = [];
for(var k in Result[i]){
keys.push(k);
}
for(var k=0;k<keys.length;k++){
console.log(keys[k]+"="+ Result[i][keys[k]]);
}
console.log("key count =" +keys.length);
}
}
CHECK THIS
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
alert(Result[0][Object.keys(Result[0])[0]]);
Result[0] gets the first row
Object.keys(Result[0]) gets the keys in the first row
Object.keys(Result[0])[0] gets the first column name.
Object.keys(Result[0]).length is the column count in the first row.
Also, objects are not indexed based on a linear integer index as arrays are, so assigning ordered numbers to the unordered list of keys is not right.
A two dimensional array would look like this:
Result = [
[1,"Pyramid","One"],
{2,"Pyramid","Two"}
]
in this case, you could address each field like so: Result[row][col] thus Result[0][2] would yield One.
To access fields in an array of object use the syntax you have provided. Also, why would you want to access the fields in your objects based on id? Or why would you not use an array of arrays?
Your Result is an array of object, then you must first get an object, and then get the property of your object. This is not a multidimensional array.
You array has an object we have to convert that object to array. So converting whole var Result to newResult you can access newResult and it's component through index number
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
];
var newResult = [];
for (var i = 0; i < Result.length; i++) {
newResult[i] = [];
for (var x in Result[i]) {
if (Result[i].hasOwnProperty(x)) {
newResult[i].push(Result[i][x]);
}
};
};
console.log(newResult);
Use newResult instead of Result
You can get ID by newResult[0][0]
http://jsfiddle.net/LLz1cbok/
How do I create an empty 2D array in Javascript (without knowing how many rows or columns there will be in the new array)?
If it's a simple array var newArray = new Array(); I can assign as many elements as I want. But what about a 2D array? Can I create one without specifying the numbers of rows and columns? and how do I access the elements afterwards (myArray[0][1] or myArray[0,1])?
You can create a 6 x 6 empty array like this:
var myGrid = [...Array(6)].map(e => Array(6));
Array(6) generates an array with length = 6 and full of undefined values.
We map that array to another array full of undefined values.
In the end, we get a 6x6 grid full of undefined positions.
If you need to initialize the grid with a default value:
var value = 'foo'; // by default
var myGrid = [...Array(6)].map(e => Array(6).fill(value));
Now you have a 6 x 6 grid full of 'foo'.
Yes you can create an empty array and then push data into it. There is no need to define the length first in JavaScript. Check out jsFiddle Live Demo
Define:
const arr = [[],[]];
Push data:
arr[0][2] = 'Hi Mr.A';
arr[1][3] = 'Hi Mr.B';
Read data:
alert(arr[0][2]);
alert(arr[1][3]);
Update:
Here is also a video recommended by Brady Dowling:
Create a 2D array: ([https://www.youtube.com/watch?v=tMeDkp1J2OM][2])
There are no two dimensional arrays in Javascript.
To accomplish the effect of a two dimensional array, you use an array of arrays, also known as a jagged array (because the inner arrays can have different length).
An empty jagged array is created just like any other empty array:
var myArray = new Array();
You can also use an empty array literal:
var myArray = [];
To put any items in the jagged array, you first have to put inner arrays in it, for example like this:
myArray.push([]);
myArray[0][0] = 'hello';
You can also create an array that contains a number of empty arrays from start:
var myArray = [[],[],[]];
That gives you a jagged array without any items, but which is prepared with three inner arrays.
As it's an array of arrays, you access the items using myArray[0][1].
Say you wanted to make a 2d array (i.e. matrix) that's 100x100, you can do it in one line, like this:
var 2darray = new Array(100).fill(null).map(()=>new Array(100).fill(null));
This will create a 100x100 matrix of NULL's.
Replace the 100x100 with whatever dimensions you want, and the null's with whatever is your prefered default value, or blank for undefined.
You can use a simple for loop to create an array of the approximate size and then push more rows if need be.
const arr = [];
const n = 7;
const m = 5;
for (let i = 0; i < n; i++) {
arr.push(new Array(m).fill(0));
}
const arr = [];
const n = 7;
const m = 5;
for (let i = 0; i < n; i++) {
arr.push(new Array(m).fill(0));
}
console.log(arr);
var myArray = [
["cats","dogs","monkeys","horses"],
["apples","oranges","pears","bananas"]
];
document.write(myArray[0][2]) //returns "monkeys"
Two things:
1) The array length property improperly reports the array length if called after the var myArray = [[],[]]; statement. Technically, since the empty arrays are defined, they are getting counted by the length property, but in the spirit of the length property it really should return 0, because no non-empty elements have been added to any of the arrays.
A minimum work around is to use two nested for( in ) loops, one for the 1st array and one for the 2nd array, and to count the non-undefined elements.
2) Extending Siamak A.Motlagh example and adding a arr([2][4]) = 'Hi Mr.C'; assignment fails with an "Uncaught TypeError: Cannot set property '4' of undefined" error.
See the jsFiddle: http://jsfiddle.net/howardb1/zq8oL2ds/
Here is a copy of that code:
var arr = [[],[]];
alert( arr.length ); // wrong!
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c ); // correct
arr[0][2] = 'Hi Mr.A';
alert(arr[0][2]);
arr[1][3] = 'Hi Mr.B';
alert(arr[1][3]);
arr[2][4] = 'Hi Mr.C'; // At this point I'm getting VM558:62 Uncaught TypeError: Cannot set property '4' of undefined
alert(arr[2][4]);
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c );
Why does the third assignment fail? What about the [[],[]] creation statement told it that the first array was valid for 0 and 1, but not 2 or that 2 and 3 were ok for the second array, but not 4?
Most importantly, how would I define an Array in an Array that could hold date objects in the first and second arrays. I'm using the jQuery-UI DatePicker, which expects an array of dates, as in date objects, which I've extended to use a second date array to contain date objects that contain times so I can keep track of multiple dates, and multiple times per day.
Thanks.
The functions I use
function get_empty_2d_array(numRows, numColumnns) {
return [...Array(numRows)].map(e => Array(numColumnns));
}
function get_2d_array_filled(numRows, numColumnns, fillValue) {
return [...Array(numRows)].map(e => Array(numColumnns).fill(fillValue));
}
This also works as an expression:
var twoDarr= new Array(desiredLength);
for (i=0;i<twoDarr.length;i++) {twoDarr[i]=[];}
I don't know how it pars in terms of performance with the rest of the answers here, if you have a clue let me know in the comments.
If you don't know the length of the array beforehand pls have in mind that you can use either push([]), or splice() if you want to push/remove/replace a new element in place of an existing one.
const grid = new Array(n).fill(new Array(n))
I'm hoping my question is using the correct terminology...
Can someone explain to me how I can perform the following:
If I have an array consisting of:
Object { id=1498, brandName="Booths", quality="Standard"}
Object { id=1499, brandName="Booths", quality="Standard"}
How can I iterate throughout that array and return another array of distinct 'keys'?
Ultimately I want an array which would return something like:
[id,brandName,quality] (but the original array is going to return different keys at different times.
Have I made sense?
You can use Object.keys:
var a1 = [{ id:1498, brandName:"Booths", quality:"Standard"},
{ id:1499, brandName:"Booths", quality:"Standard"}],
a1Keys = a1.map(function(a){return Object.keys(a);});
//a1Keys now:
[['id','brandName','quality'],['id','brandName','quality']]
The keys method is described #MDN, including a shim for older browsers
var a = {"a": 1, "b": "t" };
var keys = new Array();
for(var o in a){
keys.push(o);
}
console.log(keys)
I have data being pulled in from various sources, each returning some form of JSON or similar, although, differently formatted each time. I need to get them all into one array, but I can't figure out how to do it.
The first set is an array like this:
[
Object {id="70", type="ab", dateadded="12345678"},
Object {id="85", type="ab", dateadded="87654321"}, ... more items ...
]
The second set is being pulled in from Facebook, and is like this:
[
Object {id="12341234234", created_time="12345678"},
Object {id="567856785678", created_time="87654321"}, ... more items ...
]
So, I need to alter the second set so that it has 'type', and it has 'dateadded' instead of 'created_time', and then I need to get this all into one array so it can be sorted on 'dateadded'.
How can I do this?
Use the first array's push() method:
// for each item in second array
firstArray.push(convert(item));
function convert(obj) {
// Convert obj into format compatible with first array and return it
}
Hope this helps.
Assuming you have actual valid JSON instead of what you quoted above:
var jsonOld = '[{"id":"70","type":"ab","dateadded":"12345678"},{"id":"85","type":"ab","dateadded":"87654321"}]',
jsonNew = '[{"id":"12341234234","created_time":"12345678"},{"id":"567856785678","created_time":"87654321"}]';
Then first parse these values into actual Javascript arrays:
var mainArr = JSON.parse(jsonOld),
newArr = JSON.parse(jsonNew);
(If you already have actual Javascript arrays instead of JSON strings then skip the above step.)
Then just iterate over newArr and change the properties you need changed:
for (var i = 0, il = newArr.length; i < il; i++) {
newArr[i].type = 'ab';
newArr[i].dateadded = newArr[i].created_time;
delete newArr[i].created_time;
}
And concatenate newArr into mainArr:
mainArr = mainArr.concat(newArr);
And sort on dateadded:
mainArr.sort(function(a, b) { return a.dateadded - b.dateadded; });
This will result in:
[{"id":"70","type":"ab","dateadded":"12345678"},
{"id":"12341234234","type":"ab","dateadded":"12345678"},
{"id":"85","type":"ab","dateadded":"87654321"},
{"id":"567856785678","type":"ab","dateadded":"87654321"}]
See example