如何在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 newCells=[];
对于(var i=0;i
你的意思是这样的吗
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);
}
var单元格=[
{
单元格宽度:15.55299999999,
行号:1
},
{
单元宽度:14,
行号:2
},
{
单元格宽度:14.55299999999,
行号:2
},
{
单元宽度:14,
行号:1
}
]
var totalCells=[];
对于(变量i=0;i
像这样的东西怎么样:
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;
}, []);