JavaScript iterate through an object arrays(unknown number of content array) - javascript

I am trying to iterate through an object which has unknown number of arrays and also i dont know number of data in each array because im pulling it from a database like this for example.
i can know how many arrays in object with data.length so first for loops condition will be data.length but because i dont know how many data in each array how can i decide second for loop condition ? thanks
for(var i = 0; i <= data.length; i++) {
for(var k = 0; k <= ????; k++) {
data[i][k].locationlat
}
}

So you want to iterate through a 2-dimensional array? Would something like this work?
var num_d1 = data.length;
for (var i=0; i<num_d1; i++) {
var num_d2 = data[i].length;
for (var k=0; k<num_d2; k++) {
console.log('Latitude: ', data[i][k].locationlat)
}
}

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 push data to array with position [i]?

For example i've created an array in a for loop:
for (i = 0; i < data.length; i++){
array[i] = {
label: bread,
color: colorArray[i]
};
}
In a child for loop i'd like to append more data to this array. What I tried:
for (r = 0; r < data[i].length; r++){
array[i].push({
data: breadTypes[r][i]
});
}
Which throws TypeError : array[i].push is not a function.
array[r] = { data: breadTypes[r][i] }; overwrites the existing data as expected.
Is there a different way to do this? Thanks!
Here array[i] is an object and push is an array method which cannot be used on an object but you can create data key in array[i] object
array[r].data = breadTypes[r];
If the second loop is not nested inside the first one then breadTypes[r][i] will throw an error since i will be be available
Just do like this:
for (i = 0; i < data.length; ++i) {
array[i].data = breadTypes[i];
}
If i understand correctly, your second for should look like this:
for (r = 0; r < data[i].length; r++){
array[i].data = breadTypes[r][i];
}

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

accessing all of my elements in a multi-dimensional array with multiple loops. Why is this coming out as undefined?

Here's what I have, I have a 3-dimensional array with variations of my name. The whole thing looks like this.
var array = [['kenny', 'Kenney'],['ken','Ken'],['kenneth', 'Kenneth']];
Now, there's nothing wrong with it from what I can tell but then comes what I would like to do. I'm just trying to utilize a for loop to just loop through all of this at once so all of these elements show up. Here's what I wrote down for myself..
for(var i = 0; i < array.length; i++) {
for(var j = 0; j < array.length[i]; j++) {
for(var k = 0; k < array.length[i][j]; k++) {
console.log(array[i][j][k]);
}
}
};
What comes back is undefined. What exactly am I doing wrong? Thanks in advance, guys.
You have 2 issues here. First, you are trying to go 3 "levels" deep as if this was a 3-dimensional array, but it is only 2-dimensional.
You also need to do array[i].length instead of array.length[i]
var array = [
['kenny', 'Kenney'],
['ken', 'Ken'],
['kenneth', 'Kenneth']
];
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
console.log(array[i][j]);
}
};
You put the indexes in the wrong spot:
for(var i = 0; i < array.length; i++) {
for(var j = 0; j < array[i].length; j++) {
for(var k = 0; k < array[i][j].length; k++) {
console.log(array[i][j][k]);
}
}
}
The last loops is not needed, because that will go through the words in each of your items, printing word for word each element.
Each element of the first array has to be treated as an array.
var array = [['kenny', 'Kenney'],['ken','Ken'],['kenneth', 'Kenneth']];
for (var i=0; i<array.length; i++) {
for (var j=0; j < array[i].length; j++) {
console.log(array[i][j]);
}
}
Using forEach is clearer:
var array = [['kenny', 'Kenney'],['ken','Ken'],['kenneth', 'Kenneth']];
array.forEach(function(subarray) {
subarray.forEach(function(name) {
console.log(name);
});
});

how to remove object from array using javascript or angular js?

I am trying to remove object from array and get the resulted array.I am using remove function but it is not working perfectly
Here is my input
I need to remove all value of array which have "file": "Id"
here is my fiddle
for (var i = 0; i < arr.length; i++) {
for (var k = 0; i < arr[i].columns.length; i++)
arr[i].columns[0].remove()
}
Slight error in incrementing k
for(var i=0; i<arr.length;i++){
for (var k=0; k<arr[i].columns.length;k++)
delete arr[i].columns[0]
}
Updated JS Fiddle
Can you try this function to remove all value of array which have "file": "Id"
for(var i=0; i<arr.length;i++){
for (var k=0; k < arr[i].columns.length; k++){
if(arr[i].columns[k].fieldNameOrPath == 'Id'){
arr[i].columns.splice(k,1)
}
}
}
you can use Underscore.js
var result = _.map(arr, function(obj){
return {
columns: _.reject(obj['columns'], function(innerObj){
return innerObj['fieldNameOrPath'] == 'Id';
})
}
});

Categories