user2011139
user2011139

Reputation: 49

Structuring Javascript Array Data

hope I can get some help here.

I have a javascript array that looks like so:

var stages = ['Stage 1', 'Stage 1', 'Stage 2', 'Stage 3', 'Stage 1'];
var stageValues = [10, 20, 10, 30, 50];

What I would like to achieve is to take the above data and have it transformed into something like this:

Stage 1: 10, 20, 50
Stage 2: 10
Stage 3: 30

Kind of a bit stumped on how to do this... Any ideas would be appreciated.

Thank you.

Upvotes: 0

Views: 33

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386654

A solution with Array.prototype.reduce:

var stages = ['Stage 1', 'Stage 1', 'Stage 2', 'Stage 3', 'Stage 1'],
    stageValues = [10, 20, 10, 30, 50],
    obj = stages.reduce(function (r, a, i) {
        r[a] = r[a] || [];
        i in stageValues && r[a].push(stageValues[i]);
        return r;
    }, {});
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

Upvotes: 0

isanco
isanco

Reputation: 86

Here is a possible solution. The function returns an object key/value where each key is an element of the first array and the value is an array made of corresponding elements of the second array.

function joint_arrays(arr1,arr2) {  
  toR = {};
  if (arr1.length===arr2.length){    
    for (var i=0;i<arr1.length;i++) {
      if (arr1[i] in toR) {
        toR[arr1[i]].push(arr2[i]);
      }
      else {
        toR[arr1[i]] = [arr2[i]];
      }
    }
  }
  return toR;  
}

For example:

var res= joint_arrays(stages,stageValues);
console.log(res);

returns

[object Object] {
  Stage 1: [10, 20, 50],
  Stage 2: [10],
  Stage 3: [30]
}

Upvotes: 1

Andrey
Andrey

Reputation: 4050

You could iterate over two arrays and group it. But much more easier will be the functional approach with some library like underscore or lodash

var stages = ['Stage 1', 'Stage 1', 'Stage 2', 'Stage 3', 'Stage 1'];
var stageValues = [10, 20, 10, 30, 50];

var grouped = _.groupBy(stageValues, function (elem, index) {
    return stages[index];
});

Upvotes: 0

Related Questions