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:

  1. 遍历 array1,将带有 'DTCode' 的元素和带有 'TxtID' 的元素放在 array2 的同一行,直到遍历到另一个带有 'DTCode' 的元素,以此类推。
  2. 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);

代码解释:

  1. 定义两个空数组:array2 用于存储最终结果,currentRow 用于存储每一行的数据。
  2. 使用 for 循环遍历 array1 数组。
  3. 对于每个元素,判断其是否包含 'DTCode' 或 'TxtID'。
    • 如果包含 'DTCode',将其添加到 currentRow 数组。
    • 如果包含 'TxtID',将其添加到 currentRow 数组,并检查 currentRow 是否有超过 1 个元素。如果有,则将 currentRow 添加到 array2 数组中,并将 currentRow 重置为空数组。
  4. 循环结束后,如果 currentRow 还有元素,则将其添加到 array2 数组中。
  5. 最后,打印 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 数组操作中的分组功能,并能够将其应用到您的实际项目中。

JS 数组操作: 将带有 DTCode 和 TxtID 元素分组

原文地址: https://www.cveoy.top/t/topic/g2bw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录