如何在javascript中组合数组

你好,我想合并基于数组中的唯一项目的数组。

我有的对象

totalCells = [] 

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

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

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

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

我可以循环遍历每一行,并检查行号是否相同,然后推送该单元格宽度。 有什么方法我可以确定?

我试图得到这样的输出。

 totalCells = [ { lineNumber : 1, cells : [15,16,14] }, { lineNumber : 2, cells : [17,18,14] } ] 
 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); } 

那么这样的事情呢?

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

希望这可以帮助!

你的意思是这样吗?

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