Search code examples
javascriptarraysstringobjectnumbers

Need help creating separate variables from these 2 objects in the arrays


// I wanted to create a variable to hold the month and a variable that hold the number...

var finances = [
['Jan-1999', 867886],
['Feb-1999', 984653],
['Mar-1999', 322012],
['Apr-1999', -69417],
['May-1999', 310503],
['Jun-1999', 522857],
['Jul-1999', 1033096],
['Aug-1999', 604885],
['Sep-1999', -216386],
['Oct-1999', 477532],
['Nov-1999', 893810]];

Solution

  • What you need is map() that returns a new array with the result of a function applied to your initial array. In this case your functions would either select the first element of the subarray (the date), or the second element (the number).

    var finances = [
    ['Jan-1999', 867886],
    ['Feb-1999', 984653],
    ['Mar-1999', 322012],
    ['Apr-1999', -69417],
    ['May-1999', 310503],
    ['Jun-1999', 522857],
    ['Jul-1999', 1033096],
    ['Aug-1999', 604885],
    ['Sep-1999', -216386],
    ['Oct-1999', 477532],
    ['Nov-1999', 893810]];
    
    const dates = finances.map((e) => e[0]);
    const numbers = finances.map((e) => e[1]);
    console.log(dates);
    console.log(numbers);