Search code examples
javascriptarraysjsonanychart

Resort multiple arrays into different arrays based on item's index value in JavaScript


I'm currently working with JSON data being passed back. All-in-all, I have multiple arrays, each with a key based on a specific value in the JSON object, and these are all placed in a JavaScript object.

What I need to be able to do is go through each array in the object and place each item in a different array based on its index value. So, for example, obj(name[0]) will need to be transplanted into an array - say, array_0. The other arrays need to be sorted the same way. So, obj(different_name[0]) would also need to be placed in array_0. The same needs to happen with all other values.

To illustrate the structure:

Obj {
   array0:
      [0]AName0
      [1]AName1
      [2]AName2
      [3]AName3
   array1:
      [0]BName0
      [1]BName1
      [2]Bname2
}

I would need for AName0 to be in the same array as BName0, AName1 to be in the same array as BName1, and so on. I also need to dynamically create these arrays on the fly as data will be different each time it's run (meaning a different number of arrays and items in the array).

What I'm trying to accomplish is to create a chart dynamically. The chart will have multiple data sets, and I need to dynamically create each data set based on the data that is passed back.

Here is a jsFiddle showing the basic structure of the chart and what I'm trying to accomplish: https://jsfiddle.net/6m45LL77/

Here's how I'm getting data into the array:

for (var i = 0; i < data.Details.length; ++i) {
                obj[data.Details[i].Name].push("{low: " + data.Details[i].GeolFrom + ", " +
                    "high: " + data.Details[i].GeolTo + ", " +
                    "field: " + data.Details[i].Name + "}, ");

            }

Solution

  • Here's what I did.

    First creating the example object:

    var obj = { array0: ['AName0', 'AName1', 'AName2', 'AName3'], array1: ['BName0', 'BName1', 'BName2']};
    

    Next I created a function (naive approach) that takes the object and returns an object with the new arrays.

    function transform(obj) {
      var keys = Object.keys(obj);
      var newObj = {};
      for (var k = 0; k < keys.length; k++) {
        var arr = obj[keys[k]];
        for (var i = 0; i < arr.length; i++) {
          var el = arr[i];
          if (el) {
            if (!newObj['array_' + i]) newObj['array_' + i] = [];
            newObj['array_' + i].push(el);
          }
        }
      }
      return newObj;
    }
    

    Testing this with

    console.log(transform(obj))
    

    returns the expected result within an object

    { array_0: [ 'AName0', 'BName0' ],
      array_1: [ 'BName1' ],
      array_2: [ 'AName2', 'BName2' ],
      array_3: [ 'AName3' ] }