简体   繁体   English

如何在javascript中组合数组

[英]How to combine an array in javascript

Hello I want to merge a array based on the unique item in the array.你好我想根据数组中的唯一项合并一个数组。

The object that I have我拥有的对象

totalCells = []

In this totalCells array I have several objects like this在这个 totalCells 数组中,我有几个这样的对象

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

Now I want to make a array where I have combination of array based on the lineNumber.现在我想创建一个数组,其中我有基于 lineNumber 的数组组合。

Like I have a object with lineNumber property and cellWidth collection.就像我有一个带有 lineNumber 属性和 cellWidth 集合的对象。 Can I do this ?我可以这样做吗?

I can loop through each row and check if the line number is same and then push that cellwidth.我可以遍历每一行并检查行号是否相同,然后推送该单元格宽度。 Is there any way that I can figure ?有什么办法让我想出来吗?

I'm trying to get an output like this.我正在尝试获得这样的输出。

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

What about something like this :这样的事情怎么样:

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

Hope this helps!希望这可以帮助!

Do you mean something like this?你的意思是这样的吗?

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