AngularJS scope inside a for loop - javascript

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]);
}

Related

Grabbing String From Nested Array Using Nested Loops

I am a totally new to coding and I'm practicing loops and arrays. I created an array with multiple sub arrays that contain pairs of strings. I'm trying to pull out and isolate each string using a nested for loops.
Here is my code:
const pairs = [['Blue', 'Green'],['Red', 'Orange'],['Pink', 'Purple']];
//attempting to use nested arrays to get each string from an array
function getString(arr){
//this loop should grab each array in the list of arrays
for (let i = 0; i < arr.length; i++){
console.log(i , arr[i]);
//this should assign each sub array to a new var to be iterated over
subArr = arr[i];
} for (let j = 0; j < subArr.length; j++){
console.log(j, arr[j]);
}
};
console.log(getString(pairs));
the problem is the output is of the last for loop is : ['Pink', 'Purple'] not each color extracted from the nested loops.
What am I doing wrong here?
Mirii
You should nest the for loops like this:
for (let i = 0; i < arr.length; i++) {
console.log(i, arr[i]);
//this should assign each sub array to a new var to be iterated over
subArr = arr[i];
for (let j = 0; j < subArr.length; j++) {
console.log(j, arr[j]);
}
}
How you have it, they'd run one after the other.
The solution is provided
:
function getString(arr) {
let arrResult = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
arrResult.push(arr[i][j]);
}
}
return arrResult;
}
You need to nest the loops, just like you are nesting the arrays. Also, unless you want to alter i or j, I suggest you use .forEach as it is more simple to work with.
Example:
pairs.forEach((pair, i) => {
pair.forEach((subPair, j) => {
console.log(j, subPair);
});
});
You may also make a variable, push to it within the pair.forEach function, and return it at the end of your root function.
I hope this answers your question, thank you for posting, and have a nice day. ;P
Your loops aren't actually nested: you close the first loop before starting the second one. Because subArr is a global varialbe (no let, const, or var keyword), it's still defined in the second loop, but that's not an ideal way to do things. You also need to log arr[i][j] rather than what you have.
This fixes those issues:
function getString(arr) {
//this loop should grab each array in the list of arrays
for (let i = 0; i < arr.length; i++){
//this should assign each sub array to a new var to be iterated over
let subArr = arr[i];
for (let j = 0; j < subArr.length; j++){
console.log(arr[i][j]);
}
}
};
getString(pairs);
Another issue you have is that you're calling console.log(getString(pairs)), but getString doesn't return anything, it's logging itself. If you want it to return, for example, a newline-delimited string of all the items, you could push items to an array and return them joined with a newline (or whatever character you want):
function getString(arr) {
let ret = []
//this loop should grab each array in the list of arrays
for (let i = 0; i < arr.length; i++){
//this should assign each sub array to a new var to be iterated over
let subArr = arr[i];
for (let j = 0; j < subArr.length; j++){
ret.push(arr[i][j]);
}
}
return ret.join('\n')
};
console.log(getString(pairs));
Nested loops themselves aren't ideal, since they're not as readable as using array methods. Using forEach takes much less code:
function getString (arr) {
arr.forEach(function (subArr) {
console.log(subArr[0])
console.log(subArr[1])
})
}
getString(pairs)
Or, more succinctly, you can use map:
function getString (arr) {
return arr.map(([ a, b ]) => `${a}\n${b}`).join('\n');
}
console.log(getString(pairs))
Even more succinctly, you can do this with [].flat():
const getString = (xs = []) => xs.flat().join('\n')
console.log(getString(pairs))

How to fill multidimensional array in javascript?

I tried to get this to work, but the outer loop stops after second iteration, and everything that's after it does not execute(just like it was the end of the script). I want to fill two dimensional array with any character(here i used 'q' as an example)
var A=[[],[]];
for(var i=0;i<12;i++){
for(var j=0;j<81;j++){
A[i][j]='q';
}
}
It didn't work, so i put alert(i+' '+j); to see if it's even executing, and, as i wrote before, it stops after second iteration of outer loop, and then ignores rest of the script.
All I want is to have this array filled with same character in the given range(12 rows, 81 columns in this specific case), so if there's no hope in this method, i'll be glad to see one that works.
This does the job in one line.
var A = Array(12).fill(null).map(()=>Array(81).fill('q'))
This is an array of references and a bad idea as harunurhan commented.
var A = Array(12).fill(Array(81).fill('q'));
The Array.from() method creates a new, shallow-copied Array instance
from an array-like or iterable object.
function createAndFillTwoDArray({
rows,
columns,
defaultValue
}){
return Array.from({ length:rows }, () => (
Array.from({ length:columns }, ()=> defaultValue)
))
}
console.log(createAndFillTwoDArray({rows:3, columns:9, defaultValue: 'q'}))
var A=[[], []];
^ This line declares a two dimensional array of size 1x2. Try this instead:
var A = [];
for (var i = 0; i < 12; i++) {
A[i] = [];
for (var j = 0; j < 81; j++) {
A[i][j] = 'q';
}
}
Since fill() is the most succinct and intuitive, and it works as intended for immutable values, my preference would be an outer from() and an inner fill():
Array.from({length: 12}, _ => new Array(81).fill('q'));
The best approach to fill up 2D array would be like the following
let array2D = [], row = 3, col = 3, fillValue = 1
for (let i = 0; i < row; i++){
let temp = []
for (let j = 0; j < col; j++){
temp[j] = fillValue
}
array2D.push(temp)
}
You need to initialise a new array for i each time the first loop runs, and you don't need to set the layout of the array before you create it (Remove the [], [] inside the declaration of A). Try this:
var A = [];
for (var i = 0; i < 12; i++) {
A[i] = [];
for (var j = 0; j < 81; j++) {
A[i][j] = 'q';
}
}
console.log(A);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}

Looping all objects in an array

I have an array of data as follows:
var Sonuc = [[{"ID":8,"Number":"1","Name":"Ahmet"}],
[{"ID":7,"Number":"2","Name":"Semih"}],
[{"ID":6,"Number":"3","Name":"Derviş"}],
[{"ID":8,"Number":"4","Name":"Derviş"},{"ID":9,"Number":"4","Name":"Veli"}],
[{"ID":11,"Number":"44","Name":"Zeki"},{"ID":45,"Number":"44","Name":"Veli"}]]
I tried to write datas to console for each object as follows, but it does not work:
for (var i = 0; i < 3; i++) {
for(var obj in Sonuc[i]) {
console.log(obj.Number);
};
}
How can I output the Number value for each data on console?
The problem is that you have an array or arrays, with the sub-arrays each containing one or more objects.
Your problem is you are not specifying the index for the sub-arrays. You can access the first object like this:
console.log(obj[0].Number);
That will get you some output at at least, but it is confusing exactly what data you want to get. That 3 loop makes no sense...
If you want to output all objects, then you should first loop the sub-arrays, and then loop the objects. Something like this:
var Sonuc = [[{"ID":8,"Number":"1","Name":"Ahmet"}],
[{"ID":7,"Number":"2","Name":"Semih"}],
[{"ID":6,"Number":"3","Name":"Derviş"}],
[{"ID":8,"Number":"4","Name":"Derviş"},{"ID":9,"Number":"4","Name":"Veli"}],
[{"ID":11,"Number":"44","Name":"Zeki"},{"ID":45,"Number":"44","Name":"Veli"}]];
for (var i = 0; i < Sonuc.length; i++) {
var arr = Sonuc[i];
for (var j = 0; j < arr.length; j++) {
var obj = arr[j];
console.log(obj.Number);
}
}

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.

Form an array from the for-loop

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.

Categories