用Javascript将数据数组排列成矩阵顺序

时间:2018-10-16 07:43:18

标签: javascript sorting matrix multidimensional-array underscore.js

找不到逻辑,在这里我需要将以下数据以矩阵格式排列成多维,

var data = [
        {
            "matrixData":[8,0],
            "x":8,
            "y":0,
        }, 
        {
            "matrixData":[0,4],
            "x":0,
            "y":4,
        }, 
        {
            "matrixData":[4,0],
            "x":4,
            "y":0,
        },
        {
            "matrixData":[0,0],
            "x":0,
            "y":0,
        }, 
        {
            "matrixData":[4,4],
            "x":4,
            "y":4
        }
    ]

根据行列的明智排序, 预期结果

var data = [
        [
            {
                "matrixData":[0,0],
                "x":0,
                "y":0,
            },
            {
                "matrixData":[4,0],
                "x":4,
                "y":0,
            },
            {
                "matrixData":[8,0],
                "x":8,
                "y":0,
            },
        ],
        [
            {
                "matrixData":[0,4],
                "x":0,
                "y":4,
            }, 
            {
                "matrixData":[4,4],
                "x":4,
                "y":4
            }
        ]        
    ]

这里 x 是行, y 是列,是否可以通过使用sort方法或underscore.js

2 个答案:

答案 0 :(得分:0)

您可以预先对数组进行排序,然后对对象进行分组。

var data = [{ matrixData: [8, 0], x: 8, y: 0 }, { matrixData: [0, 4], x: 0, y: 4 }, { matrixData: [4, 0], x: 4, y: 0 }, { matrixData: [0, 0], x: 0, y: 0 }, { matrixData: [4, 4], x: 4, y: 4 }],
    groups = data
        .sort(({ matrixData: a }, { matrixData: b }) => a[1] - b[1] || a[0] - b[0])
        .reduce((r, o, i, a) => {
            if (!i || a[i - 1].matrixData[1] !== o.matrixData[1]) {
                r.push([o]);
            } else{
                r[r.length - 1].push(o);
            }        
            return r;
        }, [])
        
console.log(groups);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

来源Round

var data = [
  {
    "matrixData":[8,0],
    "x":8,
    "y":0,
  }, 
  {
    "matrixData":[0,4],
    "x":0,
    "y":4,
  }, 
  {
    "matrixData":[4,0],
    "x":4,
    "y":0,
  },
  {
    "matrixData":[0,0],
    "x":0,
    "y":0,
  }, 
  {
    "matrixData":[4,4],
    "x":4,
    "y":4
  }
];
function groupBy(collection, property) {
  var i = 0, val, index,
      values = [], result = [];
  for (; i < collection.length; i++) {
    val = collection[i][property];
    index = values.indexOf(val);
    if (index > -1)
      result[index].push(collection[i]);
    else {
      values.push(val);
      result.push([collection[i]]);
    }
  }
  return result;
}

var obj = groupBy(data, "y");

console.log(obj);