Form an array from the for-loop - javascript

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.

Related

getting array value in console

I have an array (tot) with arrays in it.
I need to check each entry in (tot) for a value , which is done at console by typing AA[3] , however, when I execute it from a script, AA[3] would NOT return any value!
here is my script:
tot=["AA","AB","AC"];
AA=["1","2","3","4","5","6","7"];
AB=["1","2","3","4","5","6","7"];
AC=["1","2","3","4","5","6","7"];
for (let i = 0; i < tot.length; i++)
{
tot[i]+'[2]';
}
I have an array (tot) with arrays in it
Actually that's inaccurate. You have an array with string values inside that are not arrays. The values of the strings you have in your array match the names of some arrays. Instead of this you might want to use an object of arrays, like:
let AA=["1","2","3","4","5","6","7"];
let AB=["1","2","3","4","5","6","7"];
let AC=["1","2","3","4","5","6","7"];
let tot={AA,AB,AC};
let index = 5;
for (let key in tot) {
console.log(`${key}[${index}]: ${tot[key][index]}`);
}
You could try:
const tot = [
["1","2","3","4","5","6","7"],
["1","2","3","4","5","6","7"],
["1","2","3","4","5","6","7"]
];
for (let i = 0; i < tot.length; i++)
{
console.log(tot[i][2]);
}
Variables do not work as functions. Instead of writing variables in a loop, try:
console.log(tot);
Also, I assume you meant to do var tot = new Array(AA, AB, AC);
var AA=["1","2","3","4","5","6","7"];
var AB=["1","2","3","4","5","6","7"];
var AC=["1","2","3","4","5","6","7"];
var tot= new Array(AA,AB,AC);
for (let i = 0; i < tot.length; i++)
{
tot[i].push("2")
console.log(tot[i]);
}
To loop through every array inside tot array, you have to nest two for loops, and console.log each value in nested for loop:
const AA=["1","2","3","4","5","6","7"];
const AB=["1","2","3","4","5","6","7"];
const AC=["1","2","3","4","5","6","7"];
const tot=[AA,AB,AC];
const logArray = (tot) => {
for (let i = 0; i < tot.length; i++) {
console.warn(`tot[${i}] contains:`);
for (let j = 0; j < tot[i].length; j++) {
console.log(tot[i][j]);
}
}
};
Your code doesn't output anything, because you didn't ask it to. also that line: tot[i] + '[2]' is not correct. What exactly are you trying to do there. I changed it to add '[2]' string to each element, but doesn't seem that that is what you want.
tot=["AA","AB","AC"];
AA=["1","2","3","4","5","6","7"];
AB=["1","2","3","4","5","6","7"];
AC=["1","2","3","4","5","6","7"];
for (let i = 0; i < tot.length; i++)
{
tot[i]+='[2]';
}
console.log(tot)

The new inserted value is replacing all values in the array

I'm trying to store a value from a parameter to an array. Unfortunately, when I'm trying to push a value, it also changed the former value. So in the end, they all have same value but it shouldn't.
For example: I push "1". It store, but when I push "2", it replaced the "1"
Here is my code:
function Add(num) {
var numArr = [];
var count= 10;
for (var i = 0; i < count; i++) {
numArr.push(num);
}
console.log(numArr);
}
Make the array global, when it is inside the function, whenever the function is called a new array is created. when array is global this problem does not arises
var numArr = [];
function Add(num) {
var count = 10;
for (var i = 0; i < count; i++) {
numArr.push(num);
}
console.log(numArr);
}
Add(11)
Add(112)
The reason why the previous value is replaced is that with each function call you declare your array all over again, with no values in it var numArr = []. Move this definition outside this function and it should be just fine
var numArr = [];
const Add = (num) => {
var count= num;
for (let i = 0; i < count; i++) {
numArr.push(num);
}
return numArr
}
console.log(Add(10))
The problem is because you instantiate the array in every iteration of the loop. The simple fix is to pass the array in to the Add() function.
function Add(arr, num) {
var count = 10;
for (var i = 0; i < count; i++) {
arr.push(num);
}
}
var numArr = [];
Add(numArr, 999);
console.log(numArr);
You could alternatively declare the array outside of the function, but this ties the function logic to external variables which makes the point of the function entirely moot.
Also note that the function itself can be replaced with the Array.fill() method which does exactly the same thing, but is unsupported in IE:
var arr = new Array(10);
arr.fill(999);
console.log(arr);
The problem is you create new array when push new value.you can create global array and push value on it.
<script>
_glb_arr=[];
$(document).ready(function (){
Add(1);
Add(3);
console.log(_glb_arr);
});
function Add(val){
_glb_arr.push(val);
}
</script>

Javascript : Store data in variables by for loop

I am having some random JSON data at the moment, therefore I cannot using standrad way to do it, cannot do it one by one.
For example if i am going to store specific data as array i will do something like below
var tester = []; // store their names within a local array
for(var k = 0; i < data.result.length; i++){ //maybe 6
for(var i = 0; i < data.result.data.length; i++){ //maybe 30 times in total
tester.push(data.result[k].data[i].someNames);
}
}
But since I cannot predict how many set of data i have i can't really do something like
var tester = [];
var tester2 = [];
var tester3 = [];
var tester4 = [];
for(var i = 0; i < data.result.data.length; i++){ //maybe 30 times in total
tester.push(data.result[0].data[i].someNames);
tester2.push(data.result[1].data[i].someNames);
tester3.push(data.result[2].data[i].someNames);
tester4.push(data.result[3].data[i].someNames);
}
if there' any better way which using for loop to store these data?
Make tester a 2-dimensional array and use nested loops.
var tester = [];
for (var i = 0; i < data.result.length; i++) {
var curTester = [];
var result = data.result[i];
for (var j = 0; j < result.data.length; j++) {
curTester.push(result.data[j].someNames);
}
tester.push(curTester);
}
Some general principles:
Any time you find yourself defining variables with numeric suffixes, they should probably be an array.
When you don't know how many of something you're going to have, put them in an array.

AngularJS scope inside a for loop

var coutas = [];
for (var i = 0; i < d.length; i++) {
coutas.push(JSON.parse(d[i].coutas));
}
for (var i = 0; i < coutas.length; i++) {
$scope.coutas = coutas[i];
}
That doesn't work
what I try to do is assign the variable coutas the scope.coutas
i'm using two for loop because that :
the firt loop , It is to tour the first array,
and the second loop is to tour the seconds array
example : the firts loop tour the array 0 but inside the array 9 they are 22 objets.
i want that :
Instead of using two for loop you may solve this problem using single loop. In your solution you generate coutas array in first loop then in second loop assigned only last info of var coutas in angular variable not whole coutas.
One process can be assign whole coutas after first loop.
like:
$scope.coutas = coutas
or you can push in $scope.coutas in first loop.
like:
for (var i = 0; i < d.length; i++) {
$scope.coutas.push(d[i].coutas); // if need to parse then use JSON.parse(d[i].coutas)
}
No need to require two loop ,if u did then define $scope.coutas =[ ] and push the arrar of every looping item;
var coutas = [];
for (var i = 0; i < d.length; i++) {
coutas.push(JSON.parse(d[i].coutas));
}
$scope.coutas =[];
for (var i = 0; i < coutas.length; i++) {
$scope.coutas.push(coutas[i]);
}

Creating array of objects dynamically based on length

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.

Categories