Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中组合数组_Javascript_Arrays - Fatal编程技术网

如何在javascript中组合数组

如何在javascript中组合数组,javascript,arrays,Javascript,Arrays,你好,我想根据数组中的唯一项合并一个数组 我拥有的东西 totalCells = [] 在这个totalCells数组中,我有几个像这样的对象 totalCells = [ { cellwidth: 15.552999999999999, lineNumber: 1 }, { cellwidth: 14, lineNumber: 2 }, { cellwidth: 14.552999999999999, lineNumber

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

我拥有的东西

totalCells = []
在这个totalCells数组中,我有几个像这样的对象

totalCells = [
  {
    cellwidth: 15.552999999999999,
    lineNumber: 1
  }, 
  {
    cellwidth: 14,
    lineNumber: 2
  },
  {
    cellwidth: 14.552999999999999,
    lineNumber: 2
  }, 
  {
    cellwidth: 14,
    lineNumber: 1
  }
];
现在我想制作一个数组,其中我有一个基于行号的数组组合

就像我有一个具有lineNumber属性和cellWidth集合的对象一样。我能做这个吗

我可以循环每一行,检查行号是否相同,然后按单元格宽度。有什么办法可以让我想想吗

我试图得到这样的输出

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

你是说像这样的事吗

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

像这样的东西怎么样:

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

希望这有帮助

我想根据行号来计算你能显示你想要得到什么结果吗?你的对象无效。对象包含在{…}中,[…]仅用于数组。这是一个包含子对象的数组,子对象包含数组
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;
}, []);