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)
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))
I am creating an object with my XML data and pushing into the array. But when it coming out from the method I can see all the array value is copy of first one. Can anyone help me.
Here is my code :
var obj = {};
for(var i = 1; i < myData.length; i++) {
var myDAtt = myData[i].getElementsByTagName('D');
for(var j = 0; j < myDAtt.length; j++){
obj[myDAtt[j].getAttribute('dataIndex')] = myDAtt[j].getAttribute('V')
}
me.Rec.push(obj);
}
You need to create a new object in the top level for loop. In your case you have only one variable, for which you are adding properties and push into the array it's reference. So at the end you have one big object and pushed the reference of it into the array for many times.
for(var i = 1; i < myData.length; i++) {
var obj = {};
var myDAtt = myData[i].getElementsByTagName('D');
for(var j = 0; j < myDAtt.length; j++) {
obj[myDAtt[j].getAttribute('dataIndex')] = myDAtt[j].getAttribute('V')
}
me.Rec.push(obj);
}
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.