简体   繁体   中英

how to iterate through nested array items separately

I have a three-dimensional array, for example:

var array = [[1,0][3,3][2,1][0,8]]

and I want to do something with the first item in each sub-array, but something else with the second item in each sub-array.

So, for example, I would like to find the sum of array[0][0], array[1][0], array[2][0] and so on for array.length . But, I would like a separate result for array[0][1], array[1][1], array[2][1] , etc.

I'm still learning javascript (very slowly) and, if possible, I would like to be pointed in the right direction, rather than getting a ready-made solution. I've been looking for possible solutions, and I think I may need a nested for loop, but I'm not sure how to structure it to get all the values.

I've been trying something along the lines of:

for (var i = 0; i < array.length; i++) {
  for (var j = 0; j < array.length; j++) {
    return array[i][j];
  }
}

but I don't understand what's happening well enough to manipulate the result.

If anyone could steer me in the right direction toward finding a solution, that'd be much appreciated.

Thanks in advance.

You might consider using .reduce - on each iteration, add the first array value to a property of the accumulator, and do whatever you need to with the second array value, assigning its result to another property of the accumulator. For example, let's say for the second items, you wanted to get their product:

 const input = [[1,0],[3,3],[2,1],[0,8]]; const { sum, product } = input .reduce(({ sum=0, product=1 }, [item0, item1]) => ({ sum: sum + item0, product: product * item1 }), {}); console.log(sum, product); 

In the above code, the accumulator is an object with two properties, sum (starts at 0) and product (starts at 1). Inside the reduce , an object is returned, with the new sum being the old sum plus the first item in the array, and with the new product being the old product multiplied by the second item in the array. (of course, the resulting product is 0 because in the first sub-array, the second item is 0)

Also note that arrays always need commas separating each array item - you need to fix your input array's syntax.

Of course, you can also for loops if you have to, but I think array methods are preferable because they're more functional, have better abstraction, and don't require manual iteration. The same code with a for loop would look like this:

 const input = [[1,0],[3,3],[2,1],[0,8]]; let sum = 0; let product = 1; for (let i = 0; i < input.length; i++) { const [item0, item1] = input[i]; sum += item0; product *= item1; } console.log(sum, product); 

You just need one for-loop since you just have one array with arrays inside where you know the indexes you want to proccess. So it would be something as follows:

let sum1 = 0;
let sum2 = 0;
for(let i = 0; i < array.length; i++) {
    sum1 += array[i][0];
    sum2 += array[i][1];     
}
console.log('sum1: ', sum1);
console.log('sum2: ', sum2);

Since you asked for help with pointing you in the right direction, I would suggest you start with simple console.logs to see what's happening (comments are inline):

 var array = [[1, 0],[3, 3],[2, 1],[0, 8]]; var results = [0, 0]; // this array is to store the results of our computation for (var i = 0; i < array.length; i++) { // for each subarray in array console.log('examining subarray ', array[i]); for (var j = 0; j < array[i].length; j++) { // for each element in subarray if (j === 0) { console.log('... do something with the first element of this array, which is: ' + array[i][j]); results[j] += array[i][j] } else if (j === 1) { console.log('... do something with the second element of this array, which is: ' + array[i][j]); // do some other computation and store it in results } } } console.log('Final results are ', results); 

You made a mistake on the second line. You need to iterate through the nested array and then take the value from the main array.

 const mainArray = [[1, 0], [3, 3], [2, 1], [0, 8]]; for (let i = 0; i < mainArray.length; i++) { const nestedArray = mainArray[i] for (let j = 0; j < nestedArray.length; j++) { const value = mainArray[i][j] switch(j) { case 0: console.log(`first item of array number ${i+1} has value: ${value}`) break; case 1: console.log(`second item of array number ${i+1} has value: ${value}`) break; } } } 

Firstly the array you have posted is a 2d array not a 3d array.

And the nested for loop you have posted is perfect for what you want. Your first for statment is looping through the the frist deminsion of your array. the second is getting each index in the second array

var array = [[1,0],[3,3],[2,1],[0,8]]
for (var i = 0; i < array.length; i++) {
  //This loop over these [1,0],[3,3],[2,1],[0,8] 
  //So i on the first loop is this object [1,0] so so on
  for (var j = 0; j < array.length; j++) {
    //This will loop over the i object
    //First loop j will be 1
    //Here is where you would do something with the index i,j. 
    //Right now you are just returning 1 on the first loop
    return array[i][j];
  }
}

I hope this help your understanding

You can use a for...of loop along with destructuring like so:

for(let [a, b] of array) {
   // a will be the first item from the subarrays: array[0][0], array[1][0], ...
   // b will be the second: : array[0][1], array[1][1], ...
}

Demo:

 let array = [[1, 0], [3, 3], [2, 1], [0, 8]]; for(let [a, b] of array) { console.log("a: " + a); console.log("b: " + b); } 

  • Using a debugger within your loop would be a good way to watch and understand each step of the loop

  • Using the forEach method would be a clearer approach to loop through the array and its children

 const items = [[1, 0],[3, 3],[2, 1],[0, 8]] let results = {} items.forEach((item, index) => { // debugger; item.forEach((subItem, subIndex) => { // debugger; if (results[subIndex]) { results[subIndex] = results[subIndex] + subItem } else { results[subIndex] = subItem } }) }) console.log(results) // { 0: 6, 1: 12 } // *********EXPLANATION BELOW ************ 

 const items = [[1, 0],[3, 3],[2, 1],[0, 8]] // store results in its own key:value pair const results = {} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach // forEach is a more readable way to loop through an array items.forEach((item, index) => { // use console.log(item, index) to see the values in each loop eg first loop contains `item = [1,0]` // you can also use a debugger here which would be the easiest way to understand the iteration // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger // debugger; // loop over item (eg [1,0]) to get subItems and their index item.forEach((subItem, subIndex) => { // get the result from previous sums from `result` // and add them to the current subItem values // if there was no previous sum(ie for first entry) // use subItem as the first value. if (results[subIndex]) { results[subIndex] = results[subIndex] + subItem } else { results[subIndex] = subItem } // Below is a oneliner way to do line 16 to 20 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator // results[subIndex] = results[subIndex] ? results[subIndex] + subItem : subItem }) }) console.log(results) // { 0: 6, 1: 12 } the results of `array[0][0],array[1][0]...` are in 0 and the result of `array[0][1], array[1][1]...` are in 1 and so on. 

用来烤面条的强制性单行程。

 console.log([[1, 0], [3, 3], [2, 1], [0, 8]].reduce((p, c) => [p[0] += c[0], p[1] += c[1]])); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM