如何在javascript中组合数组 [英] How to combine an array in javascript
本文介绍了如何在javascript中组合数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我想根据数组中的唯一项合并一个数组.
Hello I want to merge a array based on the unique item in the array.
我拥有的对象
totalCells = []
在这个 totalCells 数组中,我有几个这样的对象
In this totalCells array I have several objects like this
totalCells = [
{
cellwidth: 15.552999999999999,
lineNumber: 1
},
{
cellwidth: 14,
lineNumber: 2
},
{
cellwidth: 14.552999999999999,
lineNumber: 2
},
{
cellwidth: 14,
lineNumber: 1
}
];
现在我想创建一个数组,其中包含基于 lineNumber 的数组组合.
Now I want to make a array where I have combination of array based on the lineNumber.
就像我有一个带有 lineNumber 属性和 cellWidth 集合的对象.我可以这样做吗?
Like I have a object with lineNumber property and cellWidth collection. 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);
}
这篇关于如何在javascript中组合数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文