按索引分组数组

时间:2015-11-07 03:08:01

标签: javascript arrays grouping

我有一个数组,看起来像这样:

colors = [
    [356, 11, 30, 1],
    [354, 10, 1, 1],
    [220, 15, 33, 14],
    [51, 4, 69, 31],
    [38, 4, 54, 32],
    [33, 53, 52, 33],
    [19, 28, 78, 34],
    [0, 0, 27, 36]
];

这是一组HSL颜色,其中colors[0]colors[1]colors[2]代表HSL值,colors[3]代表此颜色所属的组。我有36组颜色。

我希望能够获得每组中的颜色频率(因此计算color[3]),并且还要求每组的colors[1]

你能帮我设置我的代码吗?我已经尝试用每个组的键创建一个对象,以便更容易使用,但不能......

这里是我试图转换数组的代码,并且更容易进行求和和频率计算:

     hueGroups = {};
     for (var i = 0;i<colors.length-1;i++) {
     var group = colors[i][3];
     hueGroups[group] = colors[i];
     }

    And it gives me:
    { '1': [ 354, 10, 1, 1 ],
      '14': [ 220, 15, 33, 14 ],
      '31': [ 51, 4, 69, 31 ],
      '32': [ 38, 4, 54, 32 ],
      '33': [ 33, 53, 52, 33 ],
      '34': [ 19, 28, 78, 34 ] }

我也不想使用外部库,我见过使用Underscore.js的解决方案。

1 个答案:

答案 0 :(得分:0)

color[][3]的计数和color[][1]的总和

colors = [
    [356, 11, 30, 1],
    [354, 10, 1, 1],
    [220, 15, 33, 14],
    [51, 4, 69, 31],
    [38, 4, 54, 32],
    [33, 53, 52, 33],
    [19, 28, 78, 34],
    [0, 0, 27, 36]
];

var histogram = (new Array(37)).fill(0);
var sum_c_1 = 0;

for(var i=0;i<colors.length;i++){
  histogram[colors[i][3]]++;
  sum_c_1 += colors[i][1];
}

console.log("sum = " + sum_c_1 + ", goups = " + histogram.join(","));

适用于更正问题的代码(见下文OP的评论):

// starting at 1 to simplify things
var histogram = (new Array(37)).fill(0);
// each individual colore per group as requested
var sum_c_1 = (new Array(37)).fill(0);

for(var i=0;i<colors.length;i++){
  histogram[colors[i][3]]++;
  // just the same as with the histogram
  sum_c_1[colors[i][3]] += colors[i][1];
}

console.log("   sum = " + sum_c_1.join(",") + "\ngroups = " + histogram.join(","));

转换为Object有点复杂,因为您不应该使用数字启动密钥标识符,但不要太多:

hueGroups = {}; 
for (var i = 0;i<colors.length;i++) { 
  var group = colors[i][3];
  hueGroups["hue" + group] = colors[i];
}
console.log(JSON.stringify(hueGroups));

只需执行

即可向对象添加更多组
var newColor = [12,32,34,13]
hueGroups["hue" + (newColor[3])] = newColor;

要更新直方图和总和,您必须从头开始重新运行循环或手动更新。