如何在JavaScript中结合阵列 [英] How to combine an array in javascript
问题描述
你好,我想根据数组中的唯一项目合并一个数组。
这是我的目标。
totalCells = []
在此totalCells阵列我有几个对象,像这样
totalCells = [
{
cellwidth:15.552999999999999
行号:1
},
{
cellwidth:14
行号:2
},
{
cellwidth:14.552999999999999
行号:2
},
{
cellwidth:14
行号:1
}
];
现在我想打一个阵列基础上,LINENUMBER在那里我有阵列组合。
就像我有LINENUMBER财产和cellWidth集合对象。我可以这样做吗?
我可以遍历每一行和检查的行号相同,然后按该cellwidth。有什么办法,我可以计算?
我试图得到这样的输出。
totalCells = [
{
LINENUMBER:1,
格:[15,16,14]
},
{
LINENUMBER:2,
格:[17,18,14]
}
]
VAR newCells = [];
对于(VAR I = 0; I< totalCells.length;我++){
VAR LINENUMBER = totalCells [I] .lineNumber;
如果(!newCells [LINENUMBER]){//添加新的对象导致
newCells [LINENUMBER] = {
LINENUMBER:行号,
cellWidth:[]
};
}
//添加此cellWidth到对象
newcells [LINENUMBER] .cellWidth.push(totalCells [I] .cellWidth);
}
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 = [
{
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.
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屋!