最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to iterate each number in array and sum them with the other numbers in the same array - JS - Stack Overflow

matteradmin8PV0评论

I'm trying to sum every number in the array with the next numbers and save all results: This is my example:

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

I have to sum 2 + 3 and save it, then 2 + 3 - 6 save it, next 2 + 3 - 6 - 1 save it etc.. to the end of the array. Next the same with second index 3 - 6 and save it, 3 - 6 + 2... I know this can be done with two nested loops but don't know how exactly to do it. Where I'm wrong ?

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

I'm trying to sum every number in the array with the next numbers and save all results: This is my example:

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

I have to sum 2 + 3 and save it, then 2 + 3 - 6 save it, next 2 + 3 - 6 - 1 save it etc.. to the end of the array. Next the same with second index 3 - 6 and save it, 3 - 6 + 2... I know this can be done with two nested loops but don't know how exactly to do it. Where I'm wrong ?

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

Share Improve this question edited Oct 3, 2018 at 20:27 Ruzihm 20.3k5 gold badges39 silver badges52 bronze badges asked Oct 3, 2018 at 19:59 SimbaSimba 2752 gold badges6 silver badges22 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 5

The following uses a function to reduce an array into an array of its gradual sums.

You can call that function repeatedly while removing items from the array to sum the entire thing.

Here's a concise version:

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

And here's an expanded version for clarity.

The logic:

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

The code:

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 bined = [...accumulator, ...sums];   //Store the results
    return bined;                            //Return the results to the next iteration
  }, []);                                       //Initialize accumulator

console.log(result);

You don't need nested loops, you need a single loop with the following logic

  • Add 1st + 2nd, store it in x.
  • Add x + 3rd (which means 1st+2nd+3rd), store it in y.
  • Add y + 4th (which means 1st+2nd+3rd+4th), store it in z.
  • ... and so on.

And to do it using single loop, instead of storing them in x, y, z .. we store it in sums array.

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

Here sums[index-1] represents x/y/z from the algorithm. And we do sums[index-1] || 0 because when index is zero, it will look for sums[-1] which will be undefined so we replace it with 0.

Here's the live code ..

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

You're missing a loop. Here's your code with some modifications.

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

If we run this with that example sequence, we see these logs:

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)

And the final sums array is:

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

You could map the values by iterating the array and take a subset of the array for another mapping. Take the value of the outer array as accumulator for adding the inner values and return this value.

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

You can use two loops, and always add the last sum of the same number to the current number:

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

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far