【问题标题】:Loop through array of arrays and increment values into a new array循环遍历数组并将值递增到新数组中
【发布时间】:2022-01-19 13:53:18
【问题描述】:

我正在努力循环遍历数组数组并返回一个带有结果递增值的新数组。

这是概念:

let array1 = [array1, array2];
let array2 = [4000,5000,3000,6000];
let array3 = [3000, 15000, 9000, 1000];

let i = 0;
let newArray = []
while (i < array1.length) {
// how do I get the combined value in a new array so that newArray[0] = 7000, newArray[1] = 20000 etc.
}

Array1 来自 API,是未知数量的数组。

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    这应该适用于任意数量的子数组。这里假设array1包含4个数组。

    let array2 = [4000, 5000, 3000, 6000]
    let array3 = [3000, 15000, 9000, 500]
    let array4 = [5000, 15000, 4000, 2000]
    let array5 = [6000, 25000, 5000, 8000]
    let array1 = [array2, array3, array4, array5]
    
    const result = array1.reduce((acc, curr) => {
      return acc.map((item, index) => item + curr[index])
    })
    
    console.log(result)

    参考资料:

    【讨论】:

    • 好的,这可以完成工作,需要阅读 reduce 和 map 以了解其工作原理。
    • 它干净简单,但稍作调整:result = array1.map((arr) =&gt; arr.reduce((acc, value) =&gt; acc + value))
    【解决方案2】:

    您可能需要一个嵌套循环。因此,基本上您将迭代同时包含 array2 和 array3 的 array1,然后在 newArray 中您将查看特定索引是否具有值。如果是这样,那么您将增加前一个的价值

    let array2 = [4000, 5000, 3000, 6000];
    let array3 = [3000, 15000, 9000, 1000];
    let array1 = [array2, array3];
    let i = 0;
    let newArray = []
    while (i < array1.length) {
      for (let j = 0; j < array1[i].length; j++) {
        // if index of new array is unoccupied then set a value there 
        if (!newArray[j]) {
          newArray[j] = array1[i][j]
        } else {
          // if index is occupied then add with previous value
          newArray[j] = newArray[j] + array1[i][j]
    
        }
    
      }
      i++;
    }
    console.log(newArray)

    【讨论】:

      【解决方案3】:

      如果元素的数量是动态的,那么,

      let array1 = [[4000, 5000, 3000, 6000], [3000, 15000, 9000, 1000, 2000, 3000], [1000], [3000, 15000, 9000, 1000, 2000, 3000, 1000, 10000]];
      
      let index = 0;
      let newArray = [];
      let maxElements = Math.max(...array1.map(arr => arr.length));
      let arrayLength = array1.length;
      
      
      while (index < maxElements) {
          let total = 0;
      
          for (let arrayIndex = 0; arrayIndex < arrayLength; arrayIndex++) {
              let element = array1[arrayIndex][index]
              if (element) total += element;
          }
      
          newArray.push(total);
          index++;
      }
      
      console.log(newArray)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-15
        • 2018-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 2017-05-21
        • 1970-01-01
        相关资源
        最近更新 更多