Home > database >  How to access an inner arrays element using a for loop in javascript
How to access an inner arrays element using a for loop in javascript

Time:12-29

I have a function that accepts an array of arrays as an argument and i need to get access to a specific element of the inner array to push it to a locally scoped empty array, so that i can use reduce method to return a net total.

I can get access using the map method of the specific element in the inner array and push these elements to an array but i can not seem to achieve this using a standard for loop.

// here is the array and i require access to the totals

var finances = [
  ["Jan-2010", 884],
  ["Feb-2010", 655],
  ["Mar-2010", 1013],
  ["Apr-2010", 417],
  ["May-2010", -7503],
  ["Jun-2010", 857],
  ["Jul-2010", 3096],
  ["Aug-2010", 885],
  ["Sep-2010", -6386],
  ["Oct-2010", 532],
  ["Nov-2010", 3810],
];

function netTotal(financeArray) {
  // lets create a variable here to return the net total to the function

  let net;

  // lets create an empty array here to store all the totals to use with reduce method

  let totals = [];

  // we need to loop through the array and push element to the totals array

  for (let i = 0; i < financeArray.length; i  ) {
    let innerArrayLength = financeArray[i].length;

    for (let j = 0; j < innerArrayLength; j  ) {
      totals.push(financeArray[i][j]);
    }
  }

  // lets use the reduce method to return the net total

  // return (net = totals.reduce((prev, next) => prev   next));

  // returning the totals array to check what is pushed to this array

  return totals;
}


console.log(netTotal(finances));

// output to console 

Array(22) [ "Jan-2010", 884, "Feb-2010", 655, "Mar-2010", 1013, "Apr-2010", 417, "May-2010", -7503, … ]




The totals array should be a flat array with all the amounts as elements so reduce can work to total every amount instead running the above function i get 22 elements in a single array because the original array is 11 arrays within the outer array.

How can i use the for loop to get access to only the amounts and push each element to this new empty array.

Any help much appreciated..

CodePudding user response:

Your nested for loops cause all elements of the arrays to be pushed. Replace them with:

for (let i = 0; i < financeArray.length; i  ) {
    let innerArray = financeArray[i];
    let amount = innerArray[1]; 
    totals.push(amount);
}

Setting amount = innerArray[1] ensures you only grab the amounts and not unnecessary elements.

CodePudding user response:

You can use flatMap method.

totals = financeArray.flatMap(f => f[1]);
const total = totals.reduce((p, c) => p   c, 0);
  • Related