如何旋转JavaScript数组 [英] How to pivot a javascript array

查看:72
本文介绍了如何旋转JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个javascript数组:

I have this javascript array:

[['a', 'x', 1],
 ['a', 'y', 2],
 ['b', 'x', 3],
 ['b', 'z', 4],
 ['c', 'y', 5],
 ['c', 'z', 6]]

如何通过上方的第二列('x','y','z')将其旋转到下面的内容。

How do I pivot it to something like below with the 2nd column ('x', 'y', 'z') from above going across.

[['a', 1, 2, null],
 ['b', 3, null, 4],
 ['c', null, 5, 6]]

编辑:
对不起,我不清楚。到目前为止,答案似乎是针对x,y,z的静态长度/值。该数组将是动态的,并且在第二列中可以包含任何内容(例如, t, u, v, w而不是 x, y, z)。我想我需要先对所有可能的组合使用null填充数组,然后再输入值。

Sorry I was unclear. The answers so far seem to be referencing a static length/value for x, y, z. The array will be dynamic and can have anything in the 2nd column (ex. 't','u','v','w' instead of 'x','y','z'). I think I need to fill the array up first with nulls for all the possible combinations and then push in the values.

谢谢。.

推荐答案

按照Fabricio的评论,这是完成类似任务的方法:

Going by Fabricio's comment, here is how you can accomplish something similar:

var result = {};
for(var i=0;i< basearray.length;i++){
    if(!result[basearray[i][0]]){
        result[basearray[i][0]]={};
    }
    result[basearray[i][0]][basearray[i][1]]=basearray[i][2];
}

请注意,这返回的对象或哈希图并非严格是数组,而是数据更有条理,并且您可以根据需要将其轻松转换为数组。 这里是一个演示(请检查您的控制台)。

Note that this returns an object or hashmap, not strictly an array, but the data is more organised and it can easily be turned into an array if you so wish. Here is a demonstration (check your console).

通过添加以下代码:

var count=0;
for(var key in result){
    result[count]=[];
    result[count][0]=key;
    result[count][1]=result[key].x||null;
    result[count][2]=result[key].y||null;
    result[count][3]=result[key].z||null;
    count++;
}

您的结果对象现在可以模拟两个结构,原始数组和建议的键值对。您可以在此处查看结果: http://jsfiddle.net/9Lakw/3/

your result object now simulates both structures, your original array of arrays, and the suggested key value pairs. You can see the results here: http://jsfiddle.net/9Lakw/3/

这是结果的样子:

{
   "a":{
      "x":1,
      "y":2
   },
   "b":{
      "x":3,
      "z":4
   },
   "c":{
      "y":5,
      "z":6
   },
   "0":[
      "a",
      1,
      2,
      null
   ],
   "1":[
      "b",
      3,
      null,
      4
   ],
   "2":[
      "c",
      null,
      5,
      6
   ]
}

这篇关于如何旋转JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆