Roni
Roni

Reputation: 21

How to get data from arrays inside of array

I'm working on an project that uses React with hooks and typescript. I'm currently trying to get data from arrays inside an array that I get from my json response. Data what i log after data handling looks like this:

[
    [
        "2021-09-07",
        43
    ],
    [
        "2021-09-08",
        47
    ],
    [
        "2021-09-09",
        52
    ]
]

So the question is, how can i get the numerical values seen in the json, to an array?

EDIT: Got it working now. Had to add this:

const numbers = data.map((item: any) => item[1]);
  console.log(numbers);

Thanks alot @Ryan Le

Upvotes: 0

Views: 62

Answers (2)

Najd Feki
Najd Feki

Reputation: 36

If by numerical values you mean the second element of each array such as (43 , 47 , 52) you can simply map to a new array like this

const oldArray = [
  [
      "2021-09-07T08:53:34.4067874+00:00",
      43
  ],
  [
      "2021-09-07T09:53:34.4067881+00:00",
      47
  ],
  [
      "2021-09-07T10:53:34.4067884+00:00",
      52
  ]
]
const newArray = oldArray.map((el)=>
  el[1])
console.log(newArray)

Upvotes: 0

Ryan Le
Ryan Le

Reputation: 8412

You would map all the numbers from the original array like so:

type Data = [string, number][];

const data: Data = [
  ["2021-09-07", 43],
  ["2021-09-08", 47],
  ["2021-09-09", 52]
];

const result = data.map(item => item[1]);

console.log(result);

Upvotes: 1

Related Questions