【问题标题】:Pushing different values in 2d array to a unique array将二维数组中的不同值推送到唯一数组
【发布时间】:2020-12-15 17:38:47
【问题描述】:

我有一个二维数组(它的行数总是随机的),如下所示:

arr = [['tag4', 'example', 'project1'],
       ['tag1', 'example', 'project2'],
       ['tag3', 'example', 'project2'],
       ['tag2', 'example', 'project3']];

请注意,此数组将始终按第 3 列中的值排序,并且此数组中的行数将不一致(随机)...如何将项目的每个不同标签分组为唯一数组?

期望结果示例:

arr1 = [['tag4', 'example', 'project1']];

arr2 = [['tag1', 'example', 'project2'],
       ['tag3', 'example', 'project2']];

arr3 = [['tag2', 'exmaple', 'project3']];

另外,我如何跟踪创建的所有唯一数组?我需要知道,因为我需要在另一个函数中实现这些数组。

【问题讨论】:

  • 第三个字段的不同数量的值是否仅限于这三个值,还是也是动态的?因为如果它是动态的,试图将它们分解成它们自己的变量将会给逻辑增加更多的复杂性而不是值得的。
  • @Taplar 这些值将是动态的。

标签: javascript node.js arrays multidimensional-array


【解决方案1】:

在这种情况下使用函数every(),但您可以使用map()foreach()。一切都非常简单,前一个索引被保留,并且在每次迭代中检查它是否与当前索引匹配,如果不同,则添加一个空数组。这样,该行将始终添加到结果数组的最后一个单元格中

//original array
let arr = [
    ['tag4', 'example', 'project1', 'foo'],
    ['tag1', 'example', 'project2'],
    ['tag3', 'example', 'project2'],
    ['tag2', 'example', 'project3', 'bar']
];

// Final array
let result = [];
// last identifier
let last = null;

// loop through every item
arr.every(row => {
    if(last !== row[2]) {
        result.push([]);
    }
    // Always insert the row in the last cell of the result array
    result[result.length - 1].push(row);
    last = row[2];
    return true;
});

console.log(result);

【讨论】:

    【解决方案2】:

    另一种方法是按项目值保留分组数组。

    假设总是有三个索引。

    let arr = [['tag4', 'example', 'project1'],       ['tag1', 'example', 'project2'],       ['tag3', 'example', 'project2'],       ['tag2', 'example', 'project3']],
        result = arr.reduce((a, [tag, desc, project]) => {
          (a[project] || (a[project] = [])).push([tag, desc, project]);
          return a;
        }, Object.create(null));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      猜你喜欢
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多