【问题标题】:How to iterate each number in array and sum them with the other numbers in the same array - JS如何迭代数组中的每个数字并将它们与同一数组中的其他数字相加 - JS
【发布时间】:2018-10-03 19:59:33
【问题描述】:

我正在尝试将数组中的每个数字与下一个数字相加并保存所有结果: 这是我的例子:

var arr = [2, 3, -6, 2, -1, 6, 4];

我必须求和 2 + 3 并保存它,然后 2 + 3 - 6 保存它,然后 2 + 3 - 6 - 1 保存它等等.. 到数组的末尾。接下来与第二个索引 3 - 6 相同并保存它, 3 - 6 + 2... 我知道这可以通过两个嵌套循环来完成,但不知道该怎么做。 我哪里错了?

const sequence = [2, 3, -6, 2, -1, 2, -1, 6, 4]
const sums = [];

for (let i = 0; i < sequence.length; i++) {

  for (let z = 1; z < sequence.length; z++) {
    let previous = sequence[z - 1] + sequence[z];
    sums.push(previous + sequence[z + 1])
  }
}

console.log(sums);

【问题讨论】:

    标签: javascript arrays loops nested


    【解决方案1】:

    下面使用一个函数将reduce一个数组变成一个数组的渐进求和。

    您可以在从数组中删除项目的同时重复调用该函数以对整个事物求和。

    这是一个简洁的版本:

    var arr = [2, 3, -6, 2, -1, 6, 4];
    
    var listSums = (array) => array.reduce((a,b) => [...a, a[a.length-1]+b], [0]).slice(2);
    var listAllSums = (array) => array.reduce((a, b, index) => [...a, ...listSums(array.slice(index))], []);
    
    console.log(listAllSums(arr));

    为了清楚起见,这里有一个扩展版本。

    逻辑:

    Add the sums of [2, 3, -6, 2, -1, 6, 4] to the list
    Add the sums of [   3, -6, 2, -1, 6, 4] to the list
    Add the sums of [      -6, 2, -1, 6, 4] to the list
    ...
    Add the sums of [             -1, 6, 4] to the list
    Add the sums of [                 6, 4] to the list
    
    Output the list
    

    代码:

    var arr = [2, 3, -6, 2, -1, 6, 4];
    
    function sumArray(array) {
        var result = array.reduce(function(accumulator,currentInt) {
          var lastSum = accumulator[accumulator.length-1];   //Get current sum
          var newSum = lastSum + currentInt;                 //Add next integer
          var resultingArray = [...accumulator, newSum];     //Combine them into an array
          return resultingArray;                             //Return the new array of sums
        }, [0]);                                             //Initialize accumulator
        return result.slice(2);
    }
    
    var result = arr.reduce(function(accumulator, currentInt, index) {  //For each item in our original array
        var toSum = arr.slice(index);               //Remove x number of items from the beginning (starting with 0)
        var sums = sumArray(toSum);                 //Sum the array using the function above
        var combined = [...accumulator, ...sums];   //Store the results
        return combined;                            //Return the results to the next iteration
      }, []);                                       //Initialize accumulator
    
    console.log(result);

    【讨论】:

      【解决方案2】:

      您不需要嵌套循环,您需要具有以下逻辑的单个循环

      • 添加 1st + 2nd,将其存储在 x 中。
      • 将x + 3rd(即1st+2nd+3rd)相加,存入y。
      • 将 y + 4th(即 1st+2nd+3rd+4th)相加,存储在 z 中。
      • ...等等。

      使用单循环来完成,而不是将它们存储在 x、y、z 中。我们将其存储在 sums 数组中。

      arr.forEach((number, index) =>
          sums.push(number + (sums[index-1] || 0))
      )
      

      这里sums[index-1] 代表算法中的 x/y/z。我们使用sums[index-1] || 0,因为当索引为零时,它会查找未定义的sums[-1],因此我们将其替换为0。

      这是实时代码..

      let arr = [2, 3, -6, 2, -1, 6, 4], sums = []
      arr.forEach((number, index) =>
          sums.push(number + (sums[index-1] || 0))
      )
      
      console.log(sums.slice(1))

      【讨论】:

        【解决方案3】:

        你错过了一个循环。这是您的代码,经过一些修改。

        const sequence = [2, 3, -6, 2, -1, 2, -1, 6, 4]
        const sums = [];
        
        for (let startIndex = 0; startIndex < sequence.length; startIndex++) {
            console.log('starting from index', startIndex, `i.e. number is (${sequence[startIndex]})`);
            for (let subSequenceLen = 1; subSequenceLen < sequence.length - startIndex; subSequenceLen++) {
                console.log('subsequence length is ', subSequenceLen);
                let sum = 0;
                for (let z = startIndex; z <= startIndex + subSequenceLen; z++) {
                    sum += sequence[z];
                }
                console.log('sum is ', sum);
                sums.push(sum);
            }
        }
        
        console.log(sums);
        

        如果我们使用该示例序列运行它,我们会看到以下日志:

        starting from index 0 i.e. number is (2)
        subsequence length is  1
        sum is  5
        subsequence length is  2
        sum is  -1
        subsequence length is  3
        sum is  1
        subsequence length is  4
        sum is  0
        subsequence length is  5
        sum is  2
        subsequence length is  6
        sum is  1
        subsequence length is  7
        sum is  7
        subsequence length is  8
        sum is  11
        starting from index 1 i.e. number is (3)
        subsequence length is  1
        sum is  -3
        subsequence length is  2
        sum is  -1
        subsequence length is  3
        sum is  -2
        subsequence length is  4
        sum is  0
        subsequence length is  5
        sum is  -1
        subsequence length is  6
        sum is  5
        subsequence length is  7
        sum is  9
        starting from index 2 i.e. number is (-6)
        subsequence length is  1
        sum is  -4
        subsequence length is  2
        sum is  -5
        subsequence length is  3
        sum is  -3
        subsequence length is  4
        sum is  -4
        subsequence length is  5
        sum is  2
        subsequence length is  6
        sum is  6
        starting from index 3 i.e. number is (2)
        subsequence length is  1
        sum is  1
        subsequence length is  2
        sum is  3
        subsequence length is  3
        sum is  2
        subsequence length is  4
        sum is  8
        subsequence length is  5
        sum is  12
        starting from index 4 i.e. number is (-1)
        subsequence length is  1
        sum is  1
        subsequence length is  2
        sum is  0
        subsequence length is  3
        sum is  6
        subsequence length is  4
        sum is  10
        starting from index 5 i.e. number is (2)
        subsequence length is  1
        sum is  1
        subsequence length is  2
        sum is  7
        subsequence length is  3
        sum is  11
        starting from index 6 i.e. number is (-1)
        subsequence length is  1
        sum is  5
        subsequence length is  2
        sum is  9
        starting from index 7 i.e. number is (6)
        subsequence length is  1
        sum is  10
        starting from index 8 i.e. number is (4)
        

        最后的 sums 数组是:

        [5,-1,1,0,2,1,7,11,-3,-1,-2,0,-1,5,9,-4,-5,-3,-4,2,6,1,3,2,8,12,1,0,6,10,1,7,11,5,9,10]
        

        【讨论】:

          【解决方案4】:

          您可以通过迭代数组来映射值,并将数组的子集用于另一个映射。将外层数组的值作为内层值相加的累加器,并返回该值。

          var array = [2, 3, -6, 2, -1, 6, 4],
              result = [].concat(...array.map((s, i, a) => a.slice(i + 1).map(v => s += v)));
          
          console.log(result);
          .as-console-wrapper { max-height: 100% !important; top: 0; }

          【讨论】:

            【解决方案5】:

            您可以使用两个循环,并始终将相同数字的最后一个总和添加到当前数字:

            const sequence = [2, 3, -6, 2, -1, 2, -1, 6, 4]
            const sums = [];
            
            for (let i = 0; i < sequence.length; i++) {
            
              let lastSum = sequence[i]; // initialize with the current number in the sequence
              
              // start from the next number in the sequence
              for (let z = i + 1; z < sequence.length; z++) {
                let sum = lastSum + sequence[z]; // add the previous sum + the current number
                sums.push(sum);
                lastSum = sum; // change base to the last sum
              }  
            }
            
            console.log(sums);

            【讨论】:

              猜你喜欢
              • 2013-05-28
              • 2020-04-16
              • 1970-01-01
              • 2020-04-18
              • 1970-01-01
              • 2018-01-26
              • 1970-01-01
              • 2023-04-10
              • 2021-03-26
              相关资源
              最近更新 更多