【问题标题】:How to merge sub-sub-arrays and add their lengths by the sub-array index?如何合并子子数组并通过子数组索引添加它们的长度?
【发布时间】:2019-03-12 10:09:21
【问题描述】:

我有一个带有一些子数组的数组(下面的代码描述了每个子数组有两个子子数组的情况,这个数字可以变化,可能是五个,但在这种情况下,我们都知道它们将有五个子数组)具有不同的长度。比如:

let arrayA = [
              [['a']            , ['b','c','d']],  //lengths  1  and  3 
              [['e','f','g','z'], ['h','i','j']],  //lengths  4  and  3
              [['k','l']        , ['m','n']]       //lengths  2  and  2 
                                                   //sums     7  and  8
             ]

我们想通过它们所属的子数组的索引来添加每个子子数组的长度:

let arrayB = [[7],[8]] 

实现这一目标的最佳方法是什么?

【问题讨论】:

  • 你有什么方法来实现这个目标?为什么你认为你的方式不是最好的?
  • 我现在没有@RokoC.Buljan
  • 用 2 个值 - 0、0 创建 arrayB。解析 arrayA[i][0] 和 array[i][1] 并将长度添加到 arrayB[0] 和 arrayB[1]。你自己试过吗?
  • 还有为什么结果看起来不像[7, 8],而是[[7],[8]]?我们? 我们是谁? 名字! ;)
  • 不,你不能。您总是可以等待几天,看看谁得到了其他用户最多的支持...或者使用提供的答案进行速度测试,看看哪个实际上是最佳...回答……或者选择最易读的……或者选择更紧凑的……完全取决于你。

标签: javascript arrays sub-array


【解决方案1】:

您可以使用reduce 来汇总数组。使用forEach 循环遍历内部数组。

let arrayA = [[["a"],["b","c","d"]],[["e","f","g","z"],["h","i","j"]],[["k","l"],["m","n"]]];

let result = arrayA.reduce((c, v) => {
  v.forEach((o, i) => {
    c[i] = c[i] || [0];
    c[i][0] += o.length;
  })
  return c;
}, []);

console.log(result);

【讨论】:

    【解决方案2】:

    您可以通过使用 lenght 属性来映射总和来减少数组。然后将结果包装在另一个数组中。

    var array = [[['a'], ['b', 'c', 'd']], [['e', 'f', 'g', 'z'], ['h', 'i', 'j',]], [['k', 'l'], ['m', 'n']]],
        result = array
            .reduce((r, a) => a.map(({ length }, i) => (r[i] || 0) + length), [])
            .map(a => [a]);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案3】:

      从原始数组创建一个长度仅为第一个子数组的新数组。 然后使用 slice 创建另一个数组,该数组包含从索引 1 到原始数组长度的 elem。

      然后使用forEach 并使用index

      let arrayA = [
        [
          ['a'],
          ['b', 'c', 'd']
        ],
        [
          ['e', 'f', 'g', 'z'],
          ['h', 'i', 'j', ]
        ],
        [
          ['k', 'l'],
          ['m', 'n']
        ]
      ]
      
      let initialElem = arrayA[0].map((item) => {
        return [item.length]
      })
      let secElem = arrayA.slice(1, arrayA.length).forEach(function(item, index) {
        if (Array.isArray(item)) {
          item.forEach(function(elem, index2) {
            initialElem[index2][0] = initialElem[index2][0] + elem.length
          })
        }
      
      })
      console.log(initialElem)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-10
        • 2017-10-18
        • 2017-11-29
        • 2017-10-22
        • 1970-01-01
        • 2012-01-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多