如何合并子子数组并通过子数组索引添加它们的长度?

How to merge sub-sub-arrays and add their lengths by the sub-array index?

我有一个包含一些子数组的数组(下面的代码描述了每个子数组有两个子数组的情况,这个数字可以变化,可能是五个,但在这种情况下我们知道他们都有五个不同长度的子数组)。类似于:

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

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

可以用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);

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

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; }

创建一个长度仅为原始数组第一个子数组长度的新数组。 然后使用 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)