Let's say i have a for loop and i want to initialize multiple arrays in that loop. Can it be achieved like this?:
for (var i = 0; i < 5; i++){
var array+i = [];
}
So that the arrays that will be created are array0,array1,array2,array3,array4?
Any help would be much appreciated :)
You can use a multi dimensional array to tackle this problem:
for(var i=0;i<5;i++){
var array[i]=[];
}
which will result in:
array[0] = []
array[1] = []
array[2] = []
array[3] = []
array[4] = []
hope that helps :)
You can achieve something like that using
JavaScript Two Dimensional
Arrays
Building a MultiDimensional Array in
Javascript
JavaScript Multi-Dimensional
Arrays
JavaScript: Multi-dimensional
Array
You can create an array of arrays:
var arr = [];
for (var i = 0; i < 5; i++) {
arr[i] = [];
}
Or if it must be a global variable (probably not a good idea):
for (var i = 0; i < 5; i++) {
window["array" + i] = [];
}
You could probably eval it out,
for (var i=0;i<5;i++) {
eval("var array"+i+"=[];");
}
But eval is evil, it would make much more sense to just use a 2 dimensional array.
You can just use a two dimensional array.
Example to initialize 10 empty arrays:
let subArrays = Array.from({length: 10}, () => []);
If you're in a browser and willing to do something hacky you can use the top-level object, namely window:
for (var i = 0; i < 5; i++) {
window["array" + i] = [];
}
After doing this, you'll be able to refer to each array as array1 or whichever number you want.
This said, you should probably never actually use this method.
Related
I am trying to push objects into an array inside a for loop. The expected data structure is
[{"valueItem":"item0"}, {"valueItem":"item1"}, {"valueItem":"item2"}, {"valueItem":"item3"}, {"valueItem":"item4"}]
The code I have is
var arr = [];
var obj = {};
for(var i = 0; i < 5; i++){
arr.push(obj.valueItem = 'item'+i);
}
console.log(arr)
But the what I get back is
["item0", "item1", "item2", "item3", "item4"]
What am I doing wrong?
try:arr.push({"valueItem":"item"+i});
Ok, to clarify, you have to push an object in your array to get your expected array.
push(obj.valueItem = 'item'+i) works sortof because you are assigning inside push.
The below works ;)
var arr = [];
for(var i = 0; i < 5; i++){
var obj = {};
obj.valueItem = 'item' + i;
arr.push(obj);
}
console.log(arr)
By doing this arr.push(obj.valueItem = 'item'+i);
you are not pushing obj into the array, you are making an assignment
obj.valueItem = 'item'+i
the result of an assignment is the returned value, in this case it is item+i,
to push objects into an array do this
arr.push({
valueItem: "item0"
})
First define object, then push it to array:
var arr = [];
for(var i = 0; i < 5; i++){
arr.push({valueItem: 'item'+i});
}
console.log(arr)
Based on your try:
var arr = [];
for(var i = 0; i < 5; i++){
var obj = {};
obj.valueItem = 'item'+i
arr.push(obj);
}
console.log(arr)
Looks like you're not actually creating a new object for each loop. Maybe try:
arr.push( { valueItem: 'item'+i } );.
The {} will create a new hash object, which we would push onto the array.
In your inital code you only made one object, so the thing you were pushing was the return value of obj.valueItem='item'+i. Since the return value of a string assignment would be the actual string, you were just creating an array of strings.
Your expected result has a different object for each element. Even though they are are similar in that they have a valueItem proprerty, they are all different. So you need to create a new one on each loop iteration. You need
arr.push({valueItem:"item"+i});
which creates a new one each time.
I have an array of arrays.
I am trying to write code in javascript for following psedocode.
Take the length of array of arrays
take out each array from array and assign it to new array
like as following which is not correct.
for (var i = 0 ; i < $scope.Permissions.length; i++)
var arr + [i] = $scope.Permissions[i];
Any help?
You can also use array's builtin forEach method:
$scope.Permissions.forEach(function (arr, i) { $scope['arr' + i] = arr });
In your case it makes sense to create bunch of new arrays as properties of the $scope object:
for (var i = 0 ; i < $scope.Permissions.length; i++) {
$scope['arr' + i] = $scope.Permissions[i];
}
console.log($scope.arr0, $scope.arr1);
This question already has answers here:
Closed 10 years ago.
This question is an exact duplicate of:
How to append an array to an existing JavaScript Array?
How do you append an array to another array in JavaScript?
Other ways that a person might word this question:
Add an array to another
Concat / Concatenate arrays
Extend an array with another array
Put the contents of one array into another array
I spent some time looking for the answer to this question. Sometimes the simplest ones like these are the hardest to find answers to, so I am adding the question here hopefully with plenty of key words and phrases as per this blog post. Please feel free to answer this question with any other helpful information or edit the key words and phrases below.
If you want to modify the original array instead of returning a new array, use .push()...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply to push the individual members of arrays 2 and 3 at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
var array1 = ['a','b','c'];
var array2 = ['d','e','f'];
var array3 = ['g','h','i'];
array1.pushArrayMembers(array2, array3);
document.body.textContent = JSON.stringify(array1, null, 4);
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.
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) );