Home > Back-end >  Seperating strings & numbers in a 2D array
Seperating strings & numbers in a 2D array

Time:12-29

I'm new to JavaScript and am currently taking an online bootcamp where we're given challenges. One of these challenges is to work with 2d arrays and extract certain data from them. For example, calculating profit/losses over the entire period. I won't add the entire array that I'm working with as it's 50 lines long but it looks something like this:

var array = [
["January", 34443]
["February", 223153]
]

and so on.

I'm struggling with manipulating this data in a way that separates the months & monies into a separate array for each piece of data, like an array for months and an array for monies. Any help on this would be greatly appreciated. What I really specifically need is a keyword or a function that already exists or I can make that analyses the array and does an action based on its data type, i.e. if it's a string add it to the variable with an if statement etc. My logic is once I've done this I can start running calculations on certain indexes of the array.

I've tried something like

    for(let x = 0; x < finances.length; x  ){
        console.log(finances[x]);

    for(let y = 0; y < finances[x].length; y  ){
        console.log(finances[x][y]);

        if(finances[y] > 0){
            totalFinance = totalFinance   finances[y];
            
        }
    }
}
console.log(totalFinance);

but I'm not getting the expected result which is the total of all numbers in the array.

CodePudding user response:

If the 2D array is of 2 x n means only two columns per row then it is pretty straight forward. Just use this function to make a separate array.

let months = [];
let monies = [];

for(let i = 0; i < array.length; i  ){
    months.push(array[i][0]);
    monies.push(array[i][1]);
}

CodePudding user response:

If the format never changes, you could use map() to do it like this:

var array = [ ["January", 34443], ["February", 223153] ];

var months = array.map((e) => e[0]);
var monies = array.map((e) => e[1]);
console.log(months);
console.log(monies);

CodePudding user response:

I think you forgot to put a comma between two months data. If my thinking is right, then by putting it and run the code below, hope this might help to fulfill your target.

var data = [ ["January", 34443], ["February", 223153] ]
var month = [];
var profit = [];

for (let i = 0 ; i < data.length; i  ){
   for(let j = 0; j < data.length; j  ){
      if(typeof data[i][j] === 'string')
      {
         month.push(data[i][j]);
      }
      else{
          profit.push(data[i][j]);
      }
   }
}

console.log(month);
console.log(profit);

//Expected Output
//[
//  "January",
//  "February"
//]
//[
//  34443,
//  223153
//]

  • Related