JS 数组操作: 将带有 DTCode 和 TxtID 元素分组
JS 数组操作: 将带有 DTCode 和 TxtID 元素分组
本文将介绍如何使用 JavaScript 代码将包含 'DTCode' 和 'TxtID' 的数组元素进行分组,并将其存放在一个二维数组中,其中带有 'DTCode' 的元素放在第一列,带有 'TxtID' 的元素放在其他列。
示例数组:
var array1 = ['DTCode 5000', 'TxtID 1369', 'DTCode 6313', 'TxtID 1370', 'DTCode 9020', 'TxtID 1162', 'TxtID 11451', 'DTCode 9643', 'TxtID 1357', 'DTCode 9645', 'TxtID 1358'];
目标:
将 array1 中的元素按照以下规则分组,形成一个新的二维数组 array2:
- 遍历
array1,将带有 'DTCode' 的元素和带有 'TxtID' 的元素放在array2的同一行,直到遍历到另一个带有 'DTCode' 的元素,以此类推。 - 将
array1里带有 'DTCode' 的元素放进array2的第一列,将array1里带有 'TxtID' 的元素放进array2的第二列、第三列等。
代码实现:
var array1 = ['DTCode 5000', 'TxtID 1369', 'DTCode 6313', 'TxtID 1370', 'DTCode 9020', 'TxtID 1162', 'TxtID 11451', 'DTCode 9643', 'TxtID 1357', 'DTCode 9645', 'TxtID 1358'];
var array2 = [];
var currentRow = [];
for (var i = 0; i < array1.length; i++) {
var element = array1[i];
if (element.includes('DTCode')) {
currentRow.push(element);
} else if (element.includes('TxtID')) {
currentRow.push(element);
if (currentRow.length > 1) {
array2.push(currentRow);
currentRow = [];
}
}
}
if (currentRow.length > 0) {
array2.push(currentRow);
}
console.log(array2);
代码解释:
- 定义两个空数组:
array2用于存储最终结果,currentRow用于存储每一行的数据。 - 使用
for循环遍历array1数组。 - 对于每个元素,判断其是否包含 'DTCode' 或 'TxtID'。
- 如果包含 'DTCode',将其添加到
currentRow数组。 - 如果包含 'TxtID',将其添加到
currentRow数组,并检查currentRow是否有超过 1 个元素。如果有,则将currentRow添加到array2数组中,并将currentRow重置为空数组。
- 如果包含 'DTCode',将其添加到
- 循环结束后,如果
currentRow还有元素,则将其添加到array2数组中。 - 最后,打印
array2数组,即为所需的结果。
结果:
[ [ 'DTCode 5000', 'TxtID 1369' ],
[ 'DTCode 6313', 'TxtID 1370' ],
[ 'DTCode 9020', 'TxtID 1162', 'TxtID 11451' ],
[ 'DTCode 9643', 'TxtID 1357' ],
[ 'DTCode 9645', 'TxtID 1358' ] ]
总结:
这段代码使用循环和条件判断,将带有 'DTCode' 和 'TxtID' 的数组元素进行分组,并将其存放在二维数组中,方便后续操作。
希望本文能够帮助您理解 JavaScript 数组操作中的分组功能,并能够将其应用到您的实际项目中。
原文地址: https://www.cveoy.top/t/topic/g2bw 著作权归作者所有。请勿转载和采集!