user11390304
user11390304

Reputation:

How to get information of a one-dimensional array if there are two-dimensional coordinates?

I have a two-dimensional array.

let x = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15],[16, 17, 18, 19, 20]]

I use the Array.flat() method and get a one-dimensional array

let y = x.flat();

Can I use two-dimensional coordinates to get information from one-dimensional? let's say my coordinates are [1] [3]. Using these coordinates, how can I get information from the y array.

Upvotes: 2

Views: 103

Answers (1)

Djaouad
Djaouad

Reputation: 22776

Provided that all subarrays have the same length, denoted N below, you can use this formula:

i * N + j

That is:

x[i][j] is equal to y[i * N + j]

let x = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15],[16, 17, 18, 19, 20]];

let y = x.flat();

let N = x[0].length; // length of subarrays (subarrays are assumed to be of equal length)

for (let i = 0; i < x.length; i++) {
  for (let j = 0; j < x[i].length; j++) {
    console.log(x[i][j], ' === ', y[i * N + j]);
  }
}

Upvotes: 3

Related Questions