【问题标题】:How to combine an array in javascript如何在javascript中组合数组
【发布时间】:2016-07-17 14:22:33
【问题描述】:

您好,我想根据数组中的唯一项合并一个数组。

我拥有的对象

totalCells = []

在这个 totalCells 数组中,我有几个这样的对象

totalCells = [
  {
    cellwidth: 15.552999999999999,
    lineNumber: 1
  }, 
  {
    cellwidth: 14,
    lineNumber: 2
  },
  {
    cellwidth: 14.552999999999999,
    lineNumber: 2
  }, 
  {
    cellwidth: 14,
    lineNumber: 1
  }
];

现在我想创建一个数组,其中我有基于 lineNumber 的数组组合。

就像我有一个带有 lineNumber 属性和 cellWidth 集合的对象。我可以这样做吗?

我可以遍历每一行并检查行号是否相同,然后推动该单元格宽度。有什么办法让我想办法吗?

我正在尝试获得这样的输出。

totalCells = [
{
  lineNumber : 1,
  cells : [15,16,14]
},
{
  lineNumber : 2,
  cells : [17,18,14]
}
]

【问题讨论】:

  • 我想根据lineNumber进行concat
  • 你能说明你想要得到什么结果吗?
  • 您的对象无效。对象包含在{ ... } 中,[...] 仅用于数组。
  • 这是一个带有子对象的数组

标签: javascript arrays


【解决方案1】:
var newCells = [];
for (var i = 0; i < totalCells.length; i++) {
    var lineNumber = totalCells[i].lineNumber;
    if (!newCells[lineNumber]) { // Add new object to result
        newCells[lineNumber] = {
            lineNumber: lineNumber,
            cellWidth: []
        };
    }
    // Add this cellWidth to object
    newcells[lineNumber].cellWidth.push(totalCells[i].cellWidth);
}

【讨论】:

    【解决方案2】:

    这样的事情怎么样:

    totalCells.reduce(function(a, b) {
      if(!a[b.lineNumber]){
        a[b.lineNumber] = {
          lineNumber: b.lineNumber,
          cells: [b.cellwidth]
        }
      }
      else{
        a[b.lineNumber].cells.push(b.cellwidth);
      }
      return a;
    }, []);
    

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      你的意思是这样的吗?

      var cells = [
      {
        cellwidth: 15.552999999999999,
        lineNumber: 1
      }, 
      {
        cellwidth: 14,
        lineNumber: 2
      },
      {
        cellwidth: 14.552999999999999,
        lineNumber: 2
      }, 
      {
        cellwidth: 14,
        lineNumber: 1
      }
      ]
      
      var totalCells = [];
      for (var i = 0; i < cells.length; i++) {
          var cell = cells[i];
          if (!totalCells[cell.lineNumber]) {
              // Add object to total cells
              totalCells[cell.lineNumber] = {
                  lineNumber: cell.lineNumber,
                  cellWidth: []
              }
          }
          // Add cell width to array
          totalCells[cell.lineNumber].cellWidth.push(cell.cellwidth);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-31
        • 2021-12-03
        • 2012-07-10
        相关资源
        最近更新 更多