簡體   English   中英

如何在javascript中組合數組

[英]How to combine an array in javascript

你好我想根據數組中的唯一項合並一個數組。

我擁有的對象

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM