简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM