0

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.

3 Answers 3

1

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]
}
Sign up to request clarification or add additional context in comments.

Comments

0

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];
});

1 Comment

Wow this is actually an awesome library.. Seems to have taken a bit of the hard work away and easily grouped them.. So many thanks for pointing me to this.. Many thanks for all the other answers as well. But is there a way I can convert the resulting json object into html readable format so it can be displayed on a webpage?
0

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>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.