Simba
Simba

Reputation: 275

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

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

Upvotes: 2

Views: 1361

Answers (5)

Tyler Roper
Tyler Roper

Reputation: 21672

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

console.log(result);

Upvotes: 5

Nina Scholz
Nina Scholz

Reputation: 386550

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

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191946

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

Upvotes: 0

slider
slider

Reputation: 12990

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]

Upvotes: 1

rmn
rmn

Reputation: 1169

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

Upvotes: 1

Related Questions