swamptiger24
swamptiger24

Reputation: 87

Javascript - How to split multidimensional array data and utilise it

I have some data which I have pulled from an external file, loaded as strings and split it into arrays. I would like to now utilise this data, I'm unsure if the best way to go about doing this is to just access the parallel arrays or to create objects with 3 different named values.

I attempted to do the former, here is a picture of my data logging to console for reference:

data

And here is the code I attempted:

  for(let i = 0; i < problem.length; i++) {
   for(let j = 1; j < problem.length; j++) {
    for(let k = 2; k < problem.length; k++) {
     id = problem[i];
     posX = problem[j];
     posY= problem[k];
    }
   }
  }

Where problem is the split string array, this does not work, and I'm quite confused on the best way to manipulate this sort of data, of which i feel is a very important skill and any guidance is appreciated!

If it matters at all I will be 'hoping' to easily call upon the one set of 3 values at a later date to visualise the data.

Upvotes: 0

Views: 119

Answers (1)

Vincent
Vincent

Reputation: 4753

It's not easy to answer because you don't explain the output format you want to get (because you are not sure) and you didn't ask an accurate question, it's more about preferences, so I can tell you what I think but it may depend on each person. So I hope my answer will help you somehow.

Reading your code, I assume index 0 in the array is an id, index 1 is posX and index 2 is posY.

So, if it were me, in order to manipulate this data easily here is how I would transform the data:

data = [
  ["30", "104", "153"],
  ["31", "104", "161"],
  ["32", "104", "169"],
  ["33", "90", "165"],
  ["34", "80", "157"],
  ["35", "64", "157"],
]

const result = data.map(item => (
  {
    id: item[0],
    posX: item[1],
    posY: item[2],
  }
))

console.log("ORIGINAL DATA", data)

console.log("NEW DATA", result)

A benefit is it would allow you to do data[15].posX instead of data[15][1]

(but again, it's just my preference, there may be tens of different ways)

Upvotes: 1

Related Questions