Home > Enterprise >  Retrieve the value from a 3D array
Retrieve the value from a 3D array

Time:10-29

Let say I have a 3D array like this

[
  [
    [3.12234, 50.12322],
    [3.12332, 12.12323],
    [3.431232, 122.22317],
  ],
]

How should i code to get any one of the value in this array?

CodePudding user response:

1) You can use array indexing as:

const arr = [
  [
    [3.12234, 50.12322],
    [3.12332, 12.12323],
    [3.431232, 122.22317],
  ],
];

const valueUsingMethod1 = arr[0][0];
console.log(valueUsingMethod1);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

2) You can also use array-destructuring as

const arr = [
  [
    [3.12234, 50.12322],
    [3.12332, 12.12323],
    [3.431232, 122.22317],
  ],
];

const [[valueUsingMethod2]] = arr;
console.log(valueUsingMethod2);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

3) You can also use flat here

const arr = [
  [
    [3.12234, 50.12322],
    [3.12332, 12.12323],
    [3.431232, 122.22317],
  ],
];

const [firstValue] = arr.flat(1);
console.log(firstValue);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related