skip to Main Content

I have the following javascript (typescript) array:

[[1262304000000,0.7537], [1262563200000,0.6951], [1262649600000,0.6925]]

How can I transform it to the following using map operator? (Basically second element of the array has been converted to % value. E.g. 0.7537 to 75.37. However, I am not sure how to access the second element of the array)

[[1262304000000,75.37], [1262563200000,69.51], [1262649600000,69.25]]

2

Answers


  1. const data = [[1262304000000, 0.7537], [1262563200000, 0.6951], [1262649600000, 0.6925]];
    
    const convertedData = data.map(item => {
      const timestamp = item[0];
      const percent = item[1] * 100; // Convert the second item to a percentage
      return [timestamp, percent]; // return both items
    });
    
    console.log(convertedData);
    
    Login or Signup to reply.
  2. Each element of your array is itself an array, and therefore you can access its elements via numeric indices like v[0] for the first element and v[1] for the second:

    const a = [[1262304000000,0.7537], [1262563200000,0.6951], [1262649600000,0.6925]];
    console.log(a.map(v => [v[0], v[1] * 100]));
    // [[1262304000000, 75.37], [1262563200000, 69.51], [1262649600000, 69.25]] 
    

    But it’s also easy to use destructuring assignment to copy each element’s members into individual named parameters before using them:

    const a = [[1262304000000,0.7537], [1262563200000,0.6951], [1262649600000,0.6925]];
    console.log(a.map(([x, y]) => [x, y*100]));
    // [[1262304000000, 75.37], [1262563200000, 69.51], [1262649600000, 69.25]] 
    

    Playground link to code

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search