gpt4 book ai didi

javascript - 如何在javascript中组合数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:14:38 25 4
gpt4 key购买 nike

您好,我想根据数组中的唯一项合并数组。

我拥有的对象

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

关于javascript - 如何在javascript中组合数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36294303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com