I have the length of my previous object and i need to create a new array of objects based on the length with new key's.
Length = 3;
var newArray = [];
for(var i =0; i <3; i++){
var Object = {};
Object['newKey'] = 1;
newArray.push(Object);
}
This would eventually create newArray of Objects whose length is 3 containing something like this.. newArray[0],[1],[2].
Am i doing this correctly, please do suggest me if anything wrong or a better way to do this.
Here's what you wrote (I think), just shortened a bit (and fixed the capitalization of variable names)
var length = 3;
var newArray = [];
for( var i = 0 ; i < length ; i++ ) {
newArray.push({newKey: 1});
}
but to be honest it's unclear to me exactly what you're trying to accomplish
You could make it slightly more dynamic by referencing the variable for length.
Example updated per comments:
var length = 3,
newArray = [];
for ( var i=0; i<length; i++ ) {
var tempObj = {};
tempObj['newKey'] = 'SomeValue';
newArray.push(tempObj);
}
I didn't really do more than clean up what you have.
Related
Is there a faster way to create and zero out a matrix?
Currently, my code involves two for loops:
var nodes = new Array(ast.length);
for (var i=0; i < nodes.length; i++){
nodes[i] = new Array(ast.length);
for (var j=0; j < nodes.length; j++)
nodes[i][j]=0;
}
You could use the Array.prototype.fill method:
var nodes = Array(ast.length).fill(Array(ast.length).fill(0));
jsperf test: http://jsperf.com/fill-array-matrix
Since you asked for "faster", it looks like you can gain some speed by creating a single initalized array and then using .slice() to copy it rather than initializing each array itself:
var nodes = new Array(ast.length);
var copy = new Array(ast.length);
for (var i = 0; i < ast.length; i++) {
copy[i] = 0;
}
for (var i=0; i < nodes.length; i++){
nodes[i] = copy.slice(0);
}
jsperf test: http://jsperf.com/slice-vs-for-two-d-array/2
This method looks to be 10-20% faster in all three major browsers.
You can create array of zeros once and create copies of it:
var length = 10;
var zeros = Array.apply(null, Array(length)).map(Number.prototype.valueOf, 0);
var nodes = zeros.map(function(i) {
return zeros.slice();
});
console.log(nodes);
I don't know how fast this is in terms of producing a 2d array but it is IMHO a better way that most.
Array.prototype.dim = function(){
if( this.length==2 ){
r=this.shift(); c=this.shift();
while( r-- ) this.push( new Array( c ).fill(0,0) );
return this;
}
}
In use, the 2d array is made by initialising a regular 1d array with the parameters of x,y or rows, cols as two parameters. These are then used to dimension the array and fill it with zeros at the same time.
var arr = new Array(5,7).dim();
console.log(arr[4]);
The array then has got the desired dimension with zeros.
The output:
console.log(arr[4]);
(7) [0, 0, 0, 0, 0, 0, 0]
I hope someone finds this useful.
How can I create a multidimensional array in JavaScript?
I have:
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar = [];
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
If I do:
groupsData.name_of_bar[0]
I get errors:
TypeError: Cannot read property '0' of undefined
TypeError: Cannot set property 'a' of undefined
What am I doing wrong?
JavaScript doesn't support multidimensional arrays per se. The closest you can come is to create an array where the values in it are also arrays.
// Set this **outside** the loop so you don't overwrite it each time you go around the loop
groupsData.name_of_bar = [];
for (var i = 0; i < m; i++){
// Create a new "array" each time you go around the loop
// Use objects, not arrays, when you have named properties (instead of ordered numeric ones)
groupsData.name_of_bar[i] = {};
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
Each iteration through the loop, you are doing groupsData.name_of_bar = [];. This removes whatever else is already in there and replaces it with a blank array.
Also, when you do groupsData.name_of_bar[i]['a'], you need to create groupsData.name_of_bar[i] first.
A way to do this is:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy: data[i].xy,
});
}
Note that in JavaScript, arrays can only be numerically indexed. If you want string indexes, you need to use an object.
Also, if there are no other values in data[i], then you can simplify this even further by doing:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push(data[i]);
}
Heck, why not just use groupsData.name_of_bar = data; and lose the loop altogether?
The way you are declaring your objects are a little off. It looks like you are attempting to create an array of objects.
var groupsData = {name_of_bar: []},
m = 4,
i = 0;
for(; i < m; i++) {
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy = data[i].xy
});
}
I have a for loop in which I am getting all the values one by one but I need to form those values into one array.
Can any one let me know how to get form all the values into one array.
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
var yourArray = [];
yourArray.push(marray);
console.log(marray);
}
Output getting from the above code is : ["0123"] and ["3456"]
But the expected output is ["0123","3456"]
You are creating a new yourArray for each loop iteration. Instead of doing that, create it just once before starting the loop:
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mId);
}
Note that I have changed the code to read yourArray.push(mId) because from the question it seems that's what you want -- not yourArray.push(marray).
A more compact way of doing the same is to use the array map function like this:
var yourArray = marray.map(function(row) { return row.id; });
This last version won't work out of the box in IE 8, so if you care about that you need to take appropriate measures.
decalare variable in outside for loop..
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mid);
}
console.log(yourArray);
Initialise yourArray before the loop
Try this
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mId);
}
The var yourArray is initialized to null each time you enter the loop. Define it outside loop.
as we know we can declare an array like this
for (int i=0;i<array.length;i++)
{ d[i]=new array();}
What about an object I want to declare more than 10 objects and I think it's not efficient to
write a declare statements for 10 times !!like this
car c1 = new car();
car c2= new Car();
..etc
what can I do ?
You are mixing the things a little.
var array = [];
for (var i = 0; i < 10; i++)
{
array[i] = new Car();
}
As Daniel noted, you can even use Array.push() in this way:
var array = [];
for (var i = 0; i < 10; i++)
{
array.push(new Car());
}
The point is that you declare the array with var array = [] (or with var array = new Array(), see the differences here What’s the difference between "Array()" and "[]" while declaring a JavaScript array?) and you set the items at the index you want (in Javascript arrays are dynamicly sized)
Use an array of objects like:
var cars = [];
for (var i = 0; i < 10; i++) {
cars.push(new Car());
}
Hum, what you're doing in your first example is declaring an array of array. To create an array, simply do
var a = [];
To create and maintain many objects, put them in that array:
for(var i = 0; i < 10; i++)
a[i] = new Car();
car[0].drive(); //Drive first car
You can:
use eval (it was designed for things like this)
use an array of objects
for (var i=1,n=3; i<n; i++)
eval("c" + i + "= new Car()");
var a = [];
for (var i=1,n=3; i<n; i++)
a[i] = new Car();
First I have an array like:
arr = [[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a]]
I can 'flatten' it using
arr = Array.prototype.concat.apply([],arr)
or using a for-next loop and push.apply
Then I got:
[r,g,b,a,r,g,b,a,r,g,b,a,r,g,b,a,r,g,b,a]
How do I get it back to its original format as easy as possible?
var newArr = [];
while(arr.length){
newArr.push(arr.splice(0,4));
}
Something like this, perhaps:
var old = [];
for (var index = 0; index < arr.length; index+= 4)
old.push( arr.slice(index, index + 4) );