代码之家  ›  专栏  ›  技术社区  ›  Joao Alves Marrucho

如何合并子数组并按子数组索引添加其长度?

  •  0
  • Joao Alves Marrucho  · 技术社区  · 6 年前

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

    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]] 
    

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

    3 回复  |  直到 6 年前
        1
  •  2
  •   Eddie    6 年前

    你可以用 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
  •  1
  •   Nina Scholz    6 年前

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

    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
  •  1
  •   brk    6 年前

    然后使用slice创建另一个数组,该数组由索引1中的元素组成,直到它的长度与原始数组的距离为止。

    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)