Search code examples
javascriptdata-structuresjavascript-objects

How to converting an array to a dictionary in Javascript (also re-order columns into rows)?


I have the following array of arrays:

[
  [o1, c1, h1, l1 ,t1],
  [o2, c2, h2, l2, t2],
  ...
  [oN, cN, hN, lN, tN]
]

I need to convert this into an object that is structured in the following way:

{
  open:   [o1,o2,o3,o4,o5,o6,o7,o8, ... oN],
  close:  [c1,c2,c3,c4,c5,c6,c7,c8, ... cN],
  high:   [h1,h2,h3,h4,h5,h6,h7,h8, ... hN],
  low:    [l1,l2,l3,l4,l5,l6,l7,l8, ... lN],
  time:   [t1,t2,t3,t4,t5,t6,t7,t8, ... tN]
}

So this means that an additional problem that I need to solve is reorganising the columns into rows.

The following is the code that works for me:

function convertData(rawDataArray) {
  [open, close, high, low, timesignature] = [
    [],
    [],
    [],
    [],
    []
  ];
  var arrayLength = rawDataArray.length;
  for (var i = 0; i < arrayLength; i++) {
    open.push(rawDataArray[i][1])
    close.push(rawDataArray[i][2])
    high.push(rawDataArray[i][3])
    low.push(rawDataArray[i][4])
    timesignature.push(rawDataArray[i][0])
  }
  return {
  	open: open,
    close: close,
    high: high,
    low: low,
    timeSignature: timesignature
  }
}

However, my solution seems to me as a clunky and not very elegant one. I am curious to learn a way to write this in a more efficient way.


Solution

  • I assume by elegant you mean easier-to-read code and not necessarily faster performance-wise. This is where map() comes in handy because it reduces the clunky for loop into one single line.

    function convertData(rawDataArray) {
        return {
            open: rawDataArray.map(i=>i[0]),
            close: rawDataArray.map(i=>i[1]),
            high: rawDataArray.map(i=>i[2]),
            low: rawDataArray.map(i=>i[3]),
            timeSignature: rawDataArray.map(i=>i[4])
        }
    }