How to combine an array in javascript

前端 未结 3 1047
死守一世寂寞
死守一世寂寞 2020-11-22 06:56

Hello I want to merge a array based on the unique item in the array.

The object that I have

totalCells = []

In this totalCells arr

相关标签:
3条回答
  • 2020-11-22 07:19
    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);
    }
    
    0 讨论(0)
  • 2020-11-22 07:24

    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);
    }
    
    0 讨论(0)
  • 2020-11-22 07:31

    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!

    0 讨论(0)
提交回复
热议问题