Sum of Parts of An Array - JavaScriptHow do JavaScript closures work?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?How to insert an item into an array at a specific index (JavaScript)?How do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?

Why transcripts instead of degree certificates?

How can I get edges to bend to avoid crossing?

How was film developed in the late 1920s?

3D nonogram, beginner's edition

Why was Mal so quick to drop Bester in favour of Kaylee?

How fast can a ship with rotating habitats be accelerated?

Avoid using C Strings on C++ code to trim leading whitespace

Is this hogweed?

Can a US President have someone sent to prison?

The Confused Alien

What is the line crossing the Pacific Ocean that is shown on maps?

What is a macro? Difference between macro and function?

How hard is it to sell a home which is currently mortgaged?

One folder two different locations on ubuntu 18.04

What is the difference between x RadToDeg cos x div and COSC?

Is there reliable evidence that depleted uranium from the 1999 NATO bombing is causing cancer in Serbia?

Why are 120 V general receptacle circuits limited to 20 A?

Does Anosov geodesic flow imply asphericity?

Being paid less than a "junior" colleague

In native German words, is Q always followed by U, as in English?

How to solve Keil compiler 'Error: L6218E: Undefined symbol' on STM32

Averting Real Women Don’t Wear Dresses

Most importants new papers in computational complexity

Could human civilization live 150 years in a nuclear-powered aircraft carrier colony without resorting to mass killing/ cannibalism?



Sum of Parts of An Array - JavaScript


How do JavaScript closures work?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?How to insert an item into an array at a specific index (JavaScript)?How do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6















Trying to solve this challenge on codewars. According to the challenge, the parts of array:



ls = [0, 1, 3, 6, 10]



Are



ls = [0, 1, 3, 6, 10]
ls = [1, 3, 6, 10]
ls = [3, 6, 10]
ls = [6, 10]
ls = [10]
ls = []


And we need to return an array with the sums of those parts.



So my code is as follows:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;


console.log(partsSums([0, 1, 3, 6, 10]));





The issue is that it wants us to add the last sum 0 when the array is empty. So we should be getting:




[ 20, 20, 19, 16, 10, 0 ]




Instead of




[ 20, 20, 19, 16, 10]




So I tried this:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

arrayOfSums.push(0);
return arrayOfSums;

console.log(partsSums([0, 1, 3, 6, 10]));





And this:






function partsSums(ls) 
ls.push(0);
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;





But these caused execution time-out errors on Codewars:




Execution Timed Out (12000 ms)




So I also tried:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > -1)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;





But now this causes a TypeError:




TypeError: Reduce of empty array with no initial value




I am not understanding the concept of how to get 0 into the array when all of the values have been shifted out. The challenge seems to want 0 as the final "sum" of the array, even when the array is empty. But you cannot reduce an empty array - what else can I do here?



EDIT: Tried adding initial value to the reduce method:



function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b, 0);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;



Unfortunately this still fails the basic test :




expected [] to deeply equal [ 0 ]











share|improve this question
























  • don't you think you should be solving it yourself?

    – Arpit Pandey
    8 hours ago






  • 1





    I have tried to solve it myself. I don't know what else to try. I am not understanding the concept of how to add the sum of an empty array to the final array. Because you can't use reduce on an empty array. Any other ideas?

    – HappyHands31
    8 hours ago











  • Cant you just push 0 after the loop?

    – Kobe
    8 hours ago






  • 1





    This: But you cannot reduce an empty array - that is not what that error message (TypeError: Reduce of empty array with no initial value) says. In fact, it is very specific: Please re-read the documentation for reduce: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - and then reread the error message.

    – Randy Casburn
    8 hours ago






  • 1





    BINGO! But consider the iterator point too.

    – Randy Casburn
    7 hours ago

















6















Trying to solve this challenge on codewars. According to the challenge, the parts of array:



ls = [0, 1, 3, 6, 10]



Are



ls = [0, 1, 3, 6, 10]
ls = [1, 3, 6, 10]
ls = [3, 6, 10]
ls = [6, 10]
ls = [10]
ls = []


And we need to return an array with the sums of those parts.



So my code is as follows:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;


console.log(partsSums([0, 1, 3, 6, 10]));





The issue is that it wants us to add the last sum 0 when the array is empty. So we should be getting:




[ 20, 20, 19, 16, 10, 0 ]




Instead of




[ 20, 20, 19, 16, 10]




So I tried this:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

arrayOfSums.push(0);
return arrayOfSums;

console.log(partsSums([0, 1, 3, 6, 10]));





And this:






function partsSums(ls) 
ls.push(0);
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;





But these caused execution time-out errors on Codewars:




Execution Timed Out (12000 ms)




So I also tried:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > -1)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;





But now this causes a TypeError:




TypeError: Reduce of empty array with no initial value




I am not understanding the concept of how to get 0 into the array when all of the values have been shifted out. The challenge seems to want 0 as the final "sum" of the array, even when the array is empty. But you cannot reduce an empty array - what else can I do here?



EDIT: Tried adding initial value to the reduce method:



function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b, 0);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;



Unfortunately this still fails the basic test :




expected [] to deeply equal [ 0 ]











share|improve this question
























  • don't you think you should be solving it yourself?

    – Arpit Pandey
    8 hours ago






  • 1





    I have tried to solve it myself. I don't know what else to try. I am not understanding the concept of how to add the sum of an empty array to the final array. Because you can't use reduce on an empty array. Any other ideas?

    – HappyHands31
    8 hours ago











  • Cant you just push 0 after the loop?

    – Kobe
    8 hours ago






  • 1





    This: But you cannot reduce an empty array - that is not what that error message (TypeError: Reduce of empty array with no initial value) says. In fact, it is very specific: Please re-read the documentation for reduce: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - and then reread the error message.

    – Randy Casburn
    8 hours ago






  • 1





    BINGO! But consider the iterator point too.

    – Randy Casburn
    7 hours ago













6












6








6


1






Trying to solve this challenge on codewars. According to the challenge, the parts of array:



ls = [0, 1, 3, 6, 10]



Are



ls = [0, 1, 3, 6, 10]
ls = [1, 3, 6, 10]
ls = [3, 6, 10]
ls = [6, 10]
ls = [10]
ls = []


And we need to return an array with the sums of those parts.



So my code is as follows:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;


console.log(partsSums([0, 1, 3, 6, 10]));





The issue is that it wants us to add the last sum 0 when the array is empty. So we should be getting:




[ 20, 20, 19, 16, 10, 0 ]




Instead of




[ 20, 20, 19, 16, 10]




So I tried this:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

arrayOfSums.push(0);
return arrayOfSums;

console.log(partsSums([0, 1, 3, 6, 10]));





And this:






function partsSums(ls) 
ls.push(0);
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;





But these caused execution time-out errors on Codewars:




Execution Timed Out (12000 ms)




So I also tried:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > -1)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;





But now this causes a TypeError:




TypeError: Reduce of empty array with no initial value




I am not understanding the concept of how to get 0 into the array when all of the values have been shifted out. The challenge seems to want 0 as the final "sum" of the array, even when the array is empty. But you cannot reduce an empty array - what else can I do here?



EDIT: Tried adding initial value to the reduce method:



function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b, 0);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;



Unfortunately this still fails the basic test :




expected [] to deeply equal [ 0 ]











share|improve this question
















Trying to solve this challenge on codewars. According to the challenge, the parts of array:



ls = [0, 1, 3, 6, 10]



Are



ls = [0, 1, 3, 6, 10]
ls = [1, 3, 6, 10]
ls = [3, 6, 10]
ls = [6, 10]
ls = [10]
ls = []


And we need to return an array with the sums of those parts.



So my code is as follows:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;


console.log(partsSums([0, 1, 3, 6, 10]));





The issue is that it wants us to add the last sum 0 when the array is empty. So we should be getting:




[ 20, 20, 19, 16, 10, 0 ]




Instead of




[ 20, 20, 19, 16, 10]




So I tried this:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

arrayOfSums.push(0);
return arrayOfSums;

console.log(partsSums([0, 1, 3, 6, 10]));





And this:






function partsSums(ls) 
ls.push(0);
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;





But these caused execution time-out errors on Codewars:




Execution Timed Out (12000 ms)




So I also tried:






function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > -1)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;





But now this causes a TypeError:




TypeError: Reduce of empty array with no initial value




I am not understanding the concept of how to get 0 into the array when all of the values have been shifted out. The challenge seems to want 0 as the final "sum" of the array, even when the array is empty. But you cannot reduce an empty array - what else can I do here?



EDIT: Tried adding initial value to the reduce method:



function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b, 0);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;



Unfortunately this still fails the basic test :




expected [] to deeply equal [ 0 ]







function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;


console.log(partsSums([0, 1, 3, 6, 10]));





function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;


console.log(partsSums([0, 1, 3, 6, 10]));





function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

arrayOfSums.push(0);
return arrayOfSums;

console.log(partsSums([0, 1, 3, 6, 10]));





function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

arrayOfSums.push(0);
return arrayOfSums;

console.log(partsSums([0, 1, 3, 6, 10]));





function partsSums(ls) 
ls.push(0);
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;





function partsSums(ls) 
ls.push(0);
let arrayOfSums = [];
while(ls.length > 0)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;





function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > -1)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;





function partsSums(ls) 
let arrayOfSums = [];
while(ls.length > -1)
let sum = ls.reduce((a, b) => a + b);
arrayOfSums.push(sum);
ls.shift();

return arrayOfSums;






javascript arrays sum reduce






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 7 hours ago







HappyHands31

















asked 8 hours ago









HappyHands31HappyHands31

1,3853 gold badges22 silver badges41 bronze badges




1,3853 gold badges22 silver badges41 bronze badges












  • don't you think you should be solving it yourself?

    – Arpit Pandey
    8 hours ago






  • 1





    I have tried to solve it myself. I don't know what else to try. I am not understanding the concept of how to add the sum of an empty array to the final array. Because you can't use reduce on an empty array. Any other ideas?

    – HappyHands31
    8 hours ago











  • Cant you just push 0 after the loop?

    – Kobe
    8 hours ago






  • 1





    This: But you cannot reduce an empty array - that is not what that error message (TypeError: Reduce of empty array with no initial value) says. In fact, it is very specific: Please re-read the documentation for reduce: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - and then reread the error message.

    – Randy Casburn
    8 hours ago






  • 1





    BINGO! But consider the iterator point too.

    – Randy Casburn
    7 hours ago

















  • don't you think you should be solving it yourself?

    – Arpit Pandey
    8 hours ago






  • 1





    I have tried to solve it myself. I don't know what else to try. I am not understanding the concept of how to add the sum of an empty array to the final array. Because you can't use reduce on an empty array. Any other ideas?

    – HappyHands31
    8 hours ago











  • Cant you just push 0 after the loop?

    – Kobe
    8 hours ago






  • 1





    This: But you cannot reduce an empty array - that is not what that error message (TypeError: Reduce of empty array with no initial value) says. In fact, it is very specific: Please re-read the documentation for reduce: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - and then reread the error message.

    – Randy Casburn
    8 hours ago






  • 1





    BINGO! But consider the iterator point too.

    – Randy Casburn
    7 hours ago
















don't you think you should be solving it yourself?

– Arpit Pandey
8 hours ago





don't you think you should be solving it yourself?

– Arpit Pandey
8 hours ago




1




1





I have tried to solve it myself. I don't know what else to try. I am not understanding the concept of how to add the sum of an empty array to the final array. Because you can't use reduce on an empty array. Any other ideas?

– HappyHands31
8 hours ago





I have tried to solve it myself. I don't know what else to try. I am not understanding the concept of how to add the sum of an empty array to the final array. Because you can't use reduce on an empty array. Any other ideas?

– HappyHands31
8 hours ago













Cant you just push 0 after the loop?

– Kobe
8 hours ago





Cant you just push 0 after the loop?

– Kobe
8 hours ago




1




1





This: But you cannot reduce an empty array - that is not what that error message (TypeError: Reduce of empty array with no initial value) says. In fact, it is very specific: Please re-read the documentation for reduce: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - and then reread the error message.

– Randy Casburn
8 hours ago





This: But you cannot reduce an empty array - that is not what that error message (TypeError: Reduce of empty array with no initial value) says. In fact, it is very specific: Please re-read the documentation for reduce: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - and then reread the error message.

– Randy Casburn
8 hours ago




1




1





BINGO! But consider the iterator point too.

– Randy Casburn
7 hours ago





BINGO! But consider the iterator point too.

– Randy Casburn
7 hours ago












6 Answers
6






active

oldest

votes


















7














There is no reason to compute the sum over and over. On a long array this will be very inefficient ( O(n²) ) and might explain your timeout errors. Compute the sum at the beginning and then subtract each element from it in a loop.






ls = [0, 1, 3, 6, 10]

function partsSums(ls)
let sum = ls.reduce((sum, n) => sum + n, 0)
res = [sum]
for (let i = 1; i <= ls.length; i++)
sum -= ls[i-1]
res.push(sum )

return res

console.log(partsSums(ls))








share|improve this answer

























  • It works. There are some things about it that I don't understand. What is ( O(n^2) )? XOR, right?

    – HappyHands31
    7 hours ago












  • O(n²) means that the number of calculations required grows exponentially as the length of your array grows. The reduce needs to look at every element in the array and you do that for every element in the array.

    – Mark Meyer
    7 hours ago











  • still some overhead ...

    – Nina Scholz
    7 hours ago






  • 1





    @NinaScholz Are you talking about the initial reduce()? At least on chrome the overhead of the initial sum is much smaller than the penalty for unshift() in my tests.

    – Mark Meyer
    7 hours ago






  • 1





    So, to break this down a bit more, we have the first sum as 20, then within the for-loop, we create the "result" array, initializing it to 20. Then we subtract ls[i - 1] from sum. So the first sum to get pushed into the result array from the for-loop will also be 20, because ls[i - 1] in this case is 0. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.

    – HappyHands31
    7 hours ago



















3














Another solution that passed all of the tests:






function partsSums(ls) 
let result = [0],
l = ls.length - 1;

for (let i = l; i >= 0; i--)
result.push(ls[i] + result[ l - i]);

return result.reverse();



console.log(partsSums([]));
console.log(partsSums([0, 1, 3, 6, 10]));
console.log(partsSums([1, 2, 3, 4, 5, 6]));
console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








share|improve this answer




















  • 1





    That is very clever yet simple. Thx.

    – HappyHands31
    6 hours ago











  • You could also do result.unshift(ls[i] + result[0]) and avoid reverse.

    – georg
    6 hours ago






  • 1





    @georg unshift doesn't pass the test because it is slower than push+reverse

    – Fraction
    6 hours ago


















1














You could use for loop with slice and when i == 0 you can slice len + 1 which is going to return you empty array and sum will be 0.






function partsSums(arr) 
const res = [], len = arr.length
for (let i = len; i > -1; i--)
res.push(arr.slice(-i
return res;


console.log(partsSums([0, 1, 3, 6, 10]));
console.log(partsSums([1, 2, 3, 4, 5, 6]));
console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));





You can also use two double reduce and if there is no next element push zero.






function partsSums(arr) 
const sum = arr => arr.reduce((r, e) => r + e, 0);
return arr.reduce((r, e, i, a) =>
const res = sum(a.slice(i, a.length));
return r.concat(!a[i + 1] ? [res, 0] : res)
, [])


console.log(partsSums([0, 1, 3, 6, 10]));
console.log(partsSums([1, 2, 3, 4, 5, 6]));
console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








share|improve this answer
































    1














    try this with recursion :






    function partsSums(ls) 
    let sum = ls.reduce((a, b) => a + b, 0);
    return ls.length > 0 ? [sum].concat(partsSums(ls.slice(1))) : [0];


    console.log(partsSums([0, 1, 3, 6, 10]));
    console.log(partsSums([1, 2, 3, 4, 5, 6]));
    console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








    share|improve this answer






























      1














      Here's one thing you could do






      function partsSums(ls) 
      if(!ls.length) return [0];
      let prevTotal = ls.reduce((a,b) => a + b);
      return [prevTotal, ...ls.map(val => prevTotal -= val)]


      console.log(partsSums([0, 1, 3, 6, 10]));








      share|improve this answer























      • I like this also - can you please help me understand how the if(!ls.length) return [0] gets added to the end of the returned array? There aren't any loops that are reducing the length of ls?

        – HappyHands31
        7 hours ago



















      1














      You could iterate from the end and take this value plus the last inserted value of the result set.



      This approach works with a single loop and without calculating the maximum sum in advance.






      function partsSums(ls) 
      var result = [0],
      i = ls.length;

      while (i--)
      result.unshift(ls[i] + result[0]);

      return result;


      console.log(partsSums([0, 1, 3, 6, 10]));
      console.log(partsSums([]));

      .as-console-wrapper max-height: 100% !important; top: 0; 





      With push and reverse.






      function partsSums(ls) 
      var result = [0],
      l = 0,
      i = ls.length;

      while (i--) result.push(l += ls[i]);
      return result.reverse();


      console.log(partsSums([0, 1, 3, 6, 10]));
      console.log(partsSums([]));

      .as-console-wrapper max-height: 100% !important; top: 0; 








      share|improve this answer



























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56739270%2fsum-of-parts-of-an-array-javascript%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        7














        There is no reason to compute the sum over and over. On a long array this will be very inefficient ( O(n²) ) and might explain your timeout errors. Compute the sum at the beginning and then subtract each element from it in a loop.






        ls = [0, 1, 3, 6, 10]

        function partsSums(ls)
        let sum = ls.reduce((sum, n) => sum + n, 0)
        res = [sum]
        for (let i = 1; i <= ls.length; i++)
        sum -= ls[i-1]
        res.push(sum )

        return res

        console.log(partsSums(ls))








        share|improve this answer

























        • It works. There are some things about it that I don't understand. What is ( O(n^2) )? XOR, right?

          – HappyHands31
          7 hours ago












        • O(n²) means that the number of calculations required grows exponentially as the length of your array grows. The reduce needs to look at every element in the array and you do that for every element in the array.

          – Mark Meyer
          7 hours ago











        • still some overhead ...

          – Nina Scholz
          7 hours ago






        • 1





          @NinaScholz Are you talking about the initial reduce()? At least on chrome the overhead of the initial sum is much smaller than the penalty for unshift() in my tests.

          – Mark Meyer
          7 hours ago






        • 1





          So, to break this down a bit more, we have the first sum as 20, then within the for-loop, we create the "result" array, initializing it to 20. Then we subtract ls[i - 1] from sum. So the first sum to get pushed into the result array from the for-loop will also be 20, because ls[i - 1] in this case is 0. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.

          – HappyHands31
          7 hours ago
















        7














        There is no reason to compute the sum over and over. On a long array this will be very inefficient ( O(n²) ) and might explain your timeout errors. Compute the sum at the beginning and then subtract each element from it in a loop.






        ls = [0, 1, 3, 6, 10]

        function partsSums(ls)
        let sum = ls.reduce((sum, n) => sum + n, 0)
        res = [sum]
        for (let i = 1; i <= ls.length; i++)
        sum -= ls[i-1]
        res.push(sum )

        return res

        console.log(partsSums(ls))








        share|improve this answer

























        • It works. There are some things about it that I don't understand. What is ( O(n^2) )? XOR, right?

          – HappyHands31
          7 hours ago












        • O(n²) means that the number of calculations required grows exponentially as the length of your array grows. The reduce needs to look at every element in the array and you do that for every element in the array.

          – Mark Meyer
          7 hours ago











        • still some overhead ...

          – Nina Scholz
          7 hours ago






        • 1





          @NinaScholz Are you talking about the initial reduce()? At least on chrome the overhead of the initial sum is much smaller than the penalty for unshift() in my tests.

          – Mark Meyer
          7 hours ago






        • 1





          So, to break this down a bit more, we have the first sum as 20, then within the for-loop, we create the "result" array, initializing it to 20. Then we subtract ls[i - 1] from sum. So the first sum to get pushed into the result array from the for-loop will also be 20, because ls[i - 1] in this case is 0. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.

          – HappyHands31
          7 hours ago














        7












        7








        7







        There is no reason to compute the sum over and over. On a long array this will be very inefficient ( O(n²) ) and might explain your timeout errors. Compute the sum at the beginning and then subtract each element from it in a loop.






        ls = [0, 1, 3, 6, 10]

        function partsSums(ls)
        let sum = ls.reduce((sum, n) => sum + n, 0)
        res = [sum]
        for (let i = 1; i <= ls.length; i++)
        sum -= ls[i-1]
        res.push(sum )

        return res

        console.log(partsSums(ls))








        share|improve this answer















        There is no reason to compute the sum over and over. On a long array this will be very inefficient ( O(n²) ) and might explain your timeout errors. Compute the sum at the beginning and then subtract each element from it in a loop.






        ls = [0, 1, 3, 6, 10]

        function partsSums(ls)
        let sum = ls.reduce((sum, n) => sum + n, 0)
        res = [sum]
        for (let i = 1; i <= ls.length; i++)
        sum -= ls[i-1]
        res.push(sum )

        return res

        console.log(partsSums(ls))








        ls = [0, 1, 3, 6, 10]

        function partsSums(ls)
        let sum = ls.reduce((sum, n) => sum + n, 0)
        res = [sum]
        for (let i = 1; i <= ls.length; i++)
        sum -= ls[i-1]
        res.push(sum )

        return res

        console.log(partsSums(ls))





        ls = [0, 1, 3, 6, 10]

        function partsSums(ls)
        let sum = ls.reduce((sum, n) => sum + n, 0)
        res = [sum]
        for (let i = 1; i <= ls.length; i++)
        sum -= ls[i-1]
        res.push(sum )

        return res

        console.log(partsSums(ls))






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 7 hours ago

























        answered 7 hours ago









        Mark MeyerMark Meyer

        47.6k3 gold badges41 silver badges74 bronze badges




        47.6k3 gold badges41 silver badges74 bronze badges












        • It works. There are some things about it that I don't understand. What is ( O(n^2) )? XOR, right?

          – HappyHands31
          7 hours ago












        • O(n²) means that the number of calculations required grows exponentially as the length of your array grows. The reduce needs to look at every element in the array and you do that for every element in the array.

          – Mark Meyer
          7 hours ago











        • still some overhead ...

          – Nina Scholz
          7 hours ago






        • 1





          @NinaScholz Are you talking about the initial reduce()? At least on chrome the overhead of the initial sum is much smaller than the penalty for unshift() in my tests.

          – Mark Meyer
          7 hours ago






        • 1





          So, to break this down a bit more, we have the first sum as 20, then within the for-loop, we create the "result" array, initializing it to 20. Then we subtract ls[i - 1] from sum. So the first sum to get pushed into the result array from the for-loop will also be 20, because ls[i - 1] in this case is 0. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.

          – HappyHands31
          7 hours ago


















        • It works. There are some things about it that I don't understand. What is ( O(n^2) )? XOR, right?

          – HappyHands31
          7 hours ago












        • O(n²) means that the number of calculations required grows exponentially as the length of your array grows. The reduce needs to look at every element in the array and you do that for every element in the array.

          – Mark Meyer
          7 hours ago











        • still some overhead ...

          – Nina Scholz
          7 hours ago






        • 1





          @NinaScholz Are you talking about the initial reduce()? At least on chrome the overhead of the initial sum is much smaller than the penalty for unshift() in my tests.

          – Mark Meyer
          7 hours ago






        • 1





          So, to break this down a bit more, we have the first sum as 20, then within the for-loop, we create the "result" array, initializing it to 20. Then we subtract ls[i - 1] from sum. So the first sum to get pushed into the result array from the for-loop will also be 20, because ls[i - 1] in this case is 0. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.

          – HappyHands31
          7 hours ago

















        It works. There are some things about it that I don't understand. What is ( O(n^2) )? XOR, right?

        – HappyHands31
        7 hours ago






        It works. There are some things about it that I don't understand. What is ( O(n^2) )? XOR, right?

        – HappyHands31
        7 hours ago














        O(n²) means that the number of calculations required grows exponentially as the length of your array grows. The reduce needs to look at every element in the array and you do that for every element in the array.

        – Mark Meyer
        7 hours ago





        O(n²) means that the number of calculations required grows exponentially as the length of your array grows. The reduce needs to look at every element in the array and you do that for every element in the array.

        – Mark Meyer
        7 hours ago













        still some overhead ...

        – Nina Scholz
        7 hours ago





        still some overhead ...

        – Nina Scholz
        7 hours ago




        1




        1





        @NinaScholz Are you talking about the initial reduce()? At least on chrome the overhead of the initial sum is much smaller than the penalty for unshift() in my tests.

        – Mark Meyer
        7 hours ago





        @NinaScholz Are you talking about the initial reduce()? At least on chrome the overhead of the initial sum is much smaller than the penalty for unshift() in my tests.

        – Mark Meyer
        7 hours ago




        1




        1





        So, to break this down a bit more, we have the first sum as 20, then within the for-loop, we create the "result" array, initializing it to 20. Then we subtract ls[i - 1] from sum. So the first sum to get pushed into the result array from the for-loop will also be 20, because ls[i - 1] in this case is 0. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.

        – HappyHands31
        7 hours ago






        So, to break this down a bit more, we have the first sum as 20, then within the for-loop, we create the "result" array, initializing it to 20. Then we subtract ls[i - 1] from sum. So the first sum to get pushed into the result array from the for-loop will also be 20, because ls[i - 1] in this case is 0. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.

        – HappyHands31
        7 hours ago














        3














        Another solution that passed all of the tests:






        function partsSums(ls) 
        let result = [0],
        l = ls.length - 1;

        for (let i = l; i >= 0; i--)
        result.push(ls[i] + result[ l - i]);

        return result.reverse();



        console.log(partsSums([]));
        console.log(partsSums([0, 1, 3, 6, 10]));
        console.log(partsSums([1, 2, 3, 4, 5, 6]));
        console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








        share|improve this answer




















        • 1





          That is very clever yet simple. Thx.

          – HappyHands31
          6 hours ago











        • You could also do result.unshift(ls[i] + result[0]) and avoid reverse.

          – georg
          6 hours ago






        • 1





          @georg unshift doesn't pass the test because it is slower than push+reverse

          – Fraction
          6 hours ago















        3














        Another solution that passed all of the tests:






        function partsSums(ls) 
        let result = [0],
        l = ls.length - 1;

        for (let i = l; i >= 0; i--)
        result.push(ls[i] + result[ l - i]);

        return result.reverse();



        console.log(partsSums([]));
        console.log(partsSums([0, 1, 3, 6, 10]));
        console.log(partsSums([1, 2, 3, 4, 5, 6]));
        console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








        share|improve this answer




















        • 1





          That is very clever yet simple. Thx.

          – HappyHands31
          6 hours ago











        • You could also do result.unshift(ls[i] + result[0]) and avoid reverse.

          – georg
          6 hours ago






        • 1





          @georg unshift doesn't pass the test because it is slower than push+reverse

          – Fraction
          6 hours ago













        3












        3








        3







        Another solution that passed all of the tests:






        function partsSums(ls) 
        let result = [0],
        l = ls.length - 1;

        for (let i = l; i >= 0; i--)
        result.push(ls[i] + result[ l - i]);

        return result.reverse();



        console.log(partsSums([]));
        console.log(partsSums([0, 1, 3, 6, 10]));
        console.log(partsSums([1, 2, 3, 4, 5, 6]));
        console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








        share|improve this answer















        Another solution that passed all of the tests:






        function partsSums(ls) 
        let result = [0],
        l = ls.length - 1;

        for (let i = l; i >= 0; i--)
        result.push(ls[i] + result[ l - i]);

        return result.reverse();



        console.log(partsSums([]));
        console.log(partsSums([0, 1, 3, 6, 10]));
        console.log(partsSums([1, 2, 3, 4, 5, 6]));
        console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








        function partsSums(ls) 
        let result = [0],
        l = ls.length - 1;

        for (let i = l; i >= 0; i--)
        result.push(ls[i] + result[ l - i]);

        return result.reverse();



        console.log(partsSums([]));
        console.log(partsSums([0, 1, 3, 6, 10]));
        console.log(partsSums([1, 2, 3, 4, 5, 6]));
        console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));





        function partsSums(ls) 
        let result = [0],
        l = ls.length - 1;

        for (let i = l; i >= 0; i--)
        result.push(ls[i] + result[ l - i]);

        return result.reverse();



        console.log(partsSums([]));
        console.log(partsSums([0, 1, 3, 6, 10]));
        console.log(partsSums([1, 2, 3, 4, 5, 6]));
        console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 7 hours ago

























        answered 7 hours ago









        FractionFraction

        1,8702 silver badges16 bronze badges




        1,8702 silver badges16 bronze badges







        • 1





          That is very clever yet simple. Thx.

          – HappyHands31
          6 hours ago











        • You could also do result.unshift(ls[i] + result[0]) and avoid reverse.

          – georg
          6 hours ago






        • 1





          @georg unshift doesn't pass the test because it is slower than push+reverse

          – Fraction
          6 hours ago












        • 1





          That is very clever yet simple. Thx.

          – HappyHands31
          6 hours ago











        • You could also do result.unshift(ls[i] + result[0]) and avoid reverse.

          – georg
          6 hours ago






        • 1





          @georg unshift doesn't pass the test because it is slower than push+reverse

          – Fraction
          6 hours ago







        1




        1





        That is very clever yet simple. Thx.

        – HappyHands31
        6 hours ago





        That is very clever yet simple. Thx.

        – HappyHands31
        6 hours ago













        You could also do result.unshift(ls[i] + result[0]) and avoid reverse.

        – georg
        6 hours ago





        You could also do result.unshift(ls[i] + result[0]) and avoid reverse.

        – georg
        6 hours ago




        1




        1





        @georg unshift doesn't pass the test because it is slower than push+reverse

        – Fraction
        6 hours ago





        @georg unshift doesn't pass the test because it is slower than push+reverse

        – Fraction
        6 hours ago











        1














        You could use for loop with slice and when i == 0 you can slice len + 1 which is going to return you empty array and sum will be 0.






        function partsSums(arr) 
        const res = [], len = arr.length
        for (let i = len; i > -1; i--)
        res.push(arr.slice(-i
        return res;


        console.log(partsSums([0, 1, 3, 6, 10]));
        console.log(partsSums([1, 2, 3, 4, 5, 6]));
        console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));





        You can also use two double reduce and if there is no next element push zero.






        function partsSums(arr) 
        const sum = arr => arr.reduce((r, e) => r + e, 0);
        return arr.reduce((r, e, i, a) =>
        const res = sum(a.slice(i, a.length));
        return r.concat(!a[i + 1] ? [res, 0] : res)
        , [])


        console.log(partsSums([0, 1, 3, 6, 10]));
        console.log(partsSums([1, 2, 3, 4, 5, 6]));
        console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








        share|improve this answer





























          1














          You could use for loop with slice and when i == 0 you can slice len + 1 which is going to return you empty array and sum will be 0.






          function partsSums(arr) 
          const res = [], len = arr.length
          for (let i = len; i > -1; i--)
          res.push(arr.slice(-i
          return res;


          console.log(partsSums([0, 1, 3, 6, 10]));
          console.log(partsSums([1, 2, 3, 4, 5, 6]));
          console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));





          You can also use two double reduce and if there is no next element push zero.






          function partsSums(arr) 
          const sum = arr => arr.reduce((r, e) => r + e, 0);
          return arr.reduce((r, e, i, a) =>
          const res = sum(a.slice(i, a.length));
          return r.concat(!a[i + 1] ? [res, 0] : res)
          , [])


          console.log(partsSums([0, 1, 3, 6, 10]));
          console.log(partsSums([1, 2, 3, 4, 5, 6]));
          console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








          share|improve this answer



























            1












            1








            1







            You could use for loop with slice and when i == 0 you can slice len + 1 which is going to return you empty array and sum will be 0.






            function partsSums(arr) 
            const res = [], len = arr.length
            for (let i = len; i > -1; i--)
            res.push(arr.slice(-i
            return res;


            console.log(partsSums([0, 1, 3, 6, 10]));
            console.log(partsSums([1, 2, 3, 4, 5, 6]));
            console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));





            You can also use two double reduce and if there is no next element push zero.






            function partsSums(arr) 
            const sum = arr => arr.reduce((r, e) => r + e, 0);
            return arr.reduce((r, e, i, a) =>
            const res = sum(a.slice(i, a.length));
            return r.concat(!a[i + 1] ? [res, 0] : res)
            , [])


            console.log(partsSums([0, 1, 3, 6, 10]));
            console.log(partsSums([1, 2, 3, 4, 5, 6]));
            console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








            share|improve this answer















            You could use for loop with slice and when i == 0 you can slice len + 1 which is going to return you empty array and sum will be 0.






            function partsSums(arr) 
            const res = [], len = arr.length
            for (let i = len; i > -1; i--)
            res.push(arr.slice(-i
            return res;


            console.log(partsSums([0, 1, 3, 6, 10]));
            console.log(partsSums([1, 2, 3, 4, 5, 6]));
            console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));





            You can also use two double reduce and if there is no next element push zero.






            function partsSums(arr) 
            const sum = arr => arr.reduce((r, e) => r + e, 0);
            return arr.reduce((r, e, i, a) =>
            const res = sum(a.slice(i, a.length));
            return r.concat(!a[i + 1] ? [res, 0] : res)
            , [])


            console.log(partsSums([0, 1, 3, 6, 10]));
            console.log(partsSums([1, 2, 3, 4, 5, 6]));
            console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








            function partsSums(arr) 
            const res = [], len = arr.length
            for (let i = len; i > -1; i--)
            res.push(arr.slice(-i
            return res;


            console.log(partsSums([0, 1, 3, 6, 10]));
            console.log(partsSums([1, 2, 3, 4, 5, 6]));
            console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));





            function partsSums(arr) 
            const res = [], len = arr.length
            for (let i = len; i > -1; i--)
            res.push(arr.slice(-i
            return res;


            console.log(partsSums([0, 1, 3, 6, 10]));
            console.log(partsSums([1, 2, 3, 4, 5, 6]));
            console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));





            function partsSums(arr) 
            const sum = arr => arr.reduce((r, e) => r + e, 0);
            return arr.reduce((r, e, i, a) =>
            const res = sum(a.slice(i, a.length));
            return r.concat(!a[i + 1] ? [res, 0] : res)
            , [])


            console.log(partsSums([0, 1, 3, 6, 10]));
            console.log(partsSums([1, 2, 3, 4, 5, 6]));
            console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));





            function partsSums(arr) 
            const sum = arr => arr.reduce((r, e) => r + e, 0);
            return arr.reduce((r, e, i, a) =>
            const res = sum(a.slice(i, a.length));
            return r.concat(!a[i + 1] ? [res, 0] : res)
            , [])


            console.log(partsSums([0, 1, 3, 6, 10]));
            console.log(partsSums([1, 2, 3, 4, 5, 6]));
            console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 7 hours ago

























            answered 7 hours ago









            Nenad VracarNenad Vracar

            76.6k12 gold badges65 silver badges88 bronze badges




            76.6k12 gold badges65 silver badges88 bronze badges





















                1














                try this with recursion :






                function partsSums(ls) 
                let sum = ls.reduce((a, b) => a + b, 0);
                return ls.length > 0 ? [sum].concat(partsSums(ls.slice(1))) : [0];


                console.log(partsSums([0, 1, 3, 6, 10]));
                console.log(partsSums([1, 2, 3, 4, 5, 6]));
                console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








                share|improve this answer



























                  1














                  try this with recursion :






                  function partsSums(ls) 
                  let sum = ls.reduce((a, b) => a + b, 0);
                  return ls.length > 0 ? [sum].concat(partsSums(ls.slice(1))) : [0];


                  console.log(partsSums([0, 1, 3, 6, 10]));
                  console.log(partsSums([1, 2, 3, 4, 5, 6]));
                  console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








                  share|improve this answer

























                    1












                    1








                    1







                    try this with recursion :






                    function partsSums(ls) 
                    let sum = ls.reduce((a, b) => a + b, 0);
                    return ls.length > 0 ? [sum].concat(partsSums(ls.slice(1))) : [0];


                    console.log(partsSums([0, 1, 3, 6, 10]));
                    console.log(partsSums([1, 2, 3, 4, 5, 6]));
                    console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








                    share|improve this answer













                    try this with recursion :






                    function partsSums(ls) 
                    let sum = ls.reduce((a, b) => a + b, 0);
                    return ls.length > 0 ? [sum].concat(partsSums(ls.slice(1))) : [0];


                    console.log(partsSums([0, 1, 3, 6, 10]));
                    console.log(partsSums([1, 2, 3, 4, 5, 6]));
                    console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));








                    function partsSums(ls) 
                    let sum = ls.reduce((a, b) => a + b, 0);
                    return ls.length > 0 ? [sum].concat(partsSums(ls.slice(1))) : [0];


                    console.log(partsSums([0, 1, 3, 6, 10]));
                    console.log(partsSums([1, 2, 3, 4, 5, 6]));
                    console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));





                    function partsSums(ls) 
                    let sum = ls.reduce((a, b) => a + b, 0);
                    return ls.length > 0 ? [sum].concat(partsSums(ls.slice(1))) : [0];


                    console.log(partsSums([0, 1, 3, 6, 10]));
                    console.log(partsSums([1, 2, 3, 4, 5, 6]));
                    console.log(partsSums([744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]));






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 7 hours ago









                    Elma CherbElma Cherb

                    1961 silver badge10 bronze badges




                    1961 silver badge10 bronze badges





















                        1














                        Here's one thing you could do






                        function partsSums(ls) 
                        if(!ls.length) return [0];
                        let prevTotal = ls.reduce((a,b) => a + b);
                        return [prevTotal, ...ls.map(val => prevTotal -= val)]


                        console.log(partsSums([0, 1, 3, 6, 10]));








                        share|improve this answer























                        • I like this also - can you please help me understand how the if(!ls.length) return [0] gets added to the end of the returned array? There aren't any loops that are reducing the length of ls?

                          – HappyHands31
                          7 hours ago
















                        1














                        Here's one thing you could do






                        function partsSums(ls) 
                        if(!ls.length) return [0];
                        let prevTotal = ls.reduce((a,b) => a + b);
                        return [prevTotal, ...ls.map(val => prevTotal -= val)]


                        console.log(partsSums([0, 1, 3, 6, 10]));








                        share|improve this answer























                        • I like this also - can you please help me understand how the if(!ls.length) return [0] gets added to the end of the returned array? There aren't any loops that are reducing the length of ls?

                          – HappyHands31
                          7 hours ago














                        1












                        1








                        1







                        Here's one thing you could do






                        function partsSums(ls) 
                        if(!ls.length) return [0];
                        let prevTotal = ls.reduce((a,b) => a + b);
                        return [prevTotal, ...ls.map(val => prevTotal -= val)]


                        console.log(partsSums([0, 1, 3, 6, 10]));








                        share|improve this answer













                        Here's one thing you could do






                        function partsSums(ls) 
                        if(!ls.length) return [0];
                        let prevTotal = ls.reduce((a,b) => a + b);
                        return [prevTotal, ...ls.map(val => prevTotal -= val)]


                        console.log(partsSums([0, 1, 3, 6, 10]));








                        function partsSums(ls) 
                        if(!ls.length) return [0];
                        let prevTotal = ls.reduce((a,b) => a + b);
                        return [prevTotal, ...ls.map(val => prevTotal -= val)]


                        console.log(partsSums([0, 1, 3, 6, 10]));





                        function partsSums(ls) 
                        if(!ls.length) return [0];
                        let prevTotal = ls.reduce((a,b) => a + b);
                        return [prevTotal, ...ls.map(val => prevTotal -= val)]


                        console.log(partsSums([0, 1, 3, 6, 10]));






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered 7 hours ago









                        Alexandre FradetteAlexandre Fradette

                        799 bronze badges




                        799 bronze badges












                        • I like this also - can you please help me understand how the if(!ls.length) return [0] gets added to the end of the returned array? There aren't any loops that are reducing the length of ls?

                          – HappyHands31
                          7 hours ago


















                        • I like this also - can you please help me understand how the if(!ls.length) return [0] gets added to the end of the returned array? There aren't any loops that are reducing the length of ls?

                          – HappyHands31
                          7 hours ago

















                        I like this also - can you please help me understand how the if(!ls.length) return [0] gets added to the end of the returned array? There aren't any loops that are reducing the length of ls?

                        – HappyHands31
                        7 hours ago






                        I like this also - can you please help me understand how the if(!ls.length) return [0] gets added to the end of the returned array? There aren't any loops that are reducing the length of ls?

                        – HappyHands31
                        7 hours ago












                        1














                        You could iterate from the end and take this value plus the last inserted value of the result set.



                        This approach works with a single loop and without calculating the maximum sum in advance.






                        function partsSums(ls) 
                        var result = [0],
                        i = ls.length;

                        while (i--)
                        result.unshift(ls[i] + result[0]);

                        return result;


                        console.log(partsSums([0, 1, 3, 6, 10]));
                        console.log(partsSums([]));

                        .as-console-wrapper max-height: 100% !important; top: 0; 





                        With push and reverse.






                        function partsSums(ls) 
                        var result = [0],
                        l = 0,
                        i = ls.length;

                        while (i--) result.push(l += ls[i]);
                        return result.reverse();


                        console.log(partsSums([0, 1, 3, 6, 10]));
                        console.log(partsSums([]));

                        .as-console-wrapper max-height: 100% !important; top: 0; 








                        share|improve this answer





























                          1














                          You could iterate from the end and take this value plus the last inserted value of the result set.



                          This approach works with a single loop and without calculating the maximum sum in advance.






                          function partsSums(ls) 
                          var result = [0],
                          i = ls.length;

                          while (i--)
                          result.unshift(ls[i] + result[0]);

                          return result;


                          console.log(partsSums([0, 1, 3, 6, 10]));
                          console.log(partsSums([]));

                          .as-console-wrapper max-height: 100% !important; top: 0; 





                          With push and reverse.






                          function partsSums(ls) 
                          var result = [0],
                          l = 0,
                          i = ls.length;

                          while (i--) result.push(l += ls[i]);
                          return result.reverse();


                          console.log(partsSums([0, 1, 3, 6, 10]));
                          console.log(partsSums([]));

                          .as-console-wrapper max-height: 100% !important; top: 0; 








                          share|improve this answer



























                            1












                            1








                            1







                            You could iterate from the end and take this value plus the last inserted value of the result set.



                            This approach works with a single loop and without calculating the maximum sum in advance.






                            function partsSums(ls) 
                            var result = [0],
                            i = ls.length;

                            while (i--)
                            result.unshift(ls[i] + result[0]);

                            return result;


                            console.log(partsSums([0, 1, 3, 6, 10]));
                            console.log(partsSums([]));

                            .as-console-wrapper max-height: 100% !important; top: 0; 





                            With push and reverse.






                            function partsSums(ls) 
                            var result = [0],
                            l = 0,
                            i = ls.length;

                            while (i--) result.push(l += ls[i]);
                            return result.reverse();


                            console.log(partsSums([0, 1, 3, 6, 10]));
                            console.log(partsSums([]));

                            .as-console-wrapper max-height: 100% !important; top: 0; 








                            share|improve this answer















                            You could iterate from the end and take this value plus the last inserted value of the result set.



                            This approach works with a single loop and without calculating the maximum sum in advance.






                            function partsSums(ls) 
                            var result = [0],
                            i = ls.length;

                            while (i--)
                            result.unshift(ls[i] + result[0]);

                            return result;


                            console.log(partsSums([0, 1, 3, 6, 10]));
                            console.log(partsSums([]));

                            .as-console-wrapper max-height: 100% !important; top: 0; 





                            With push and reverse.






                            function partsSums(ls) 
                            var result = [0],
                            l = 0,
                            i = ls.length;

                            while (i--) result.push(l += ls[i]);
                            return result.reverse();


                            console.log(partsSums([0, 1, 3, 6, 10]));
                            console.log(partsSums([]));

                            .as-console-wrapper max-height: 100% !important; top: 0; 








                            function partsSums(ls) 
                            var result = [0],
                            i = ls.length;

                            while (i--)
                            result.unshift(ls[i] + result[0]);

                            return result;


                            console.log(partsSums([0, 1, 3, 6, 10]));
                            console.log(partsSums([]));

                            .as-console-wrapper max-height: 100% !important; top: 0; 





                            function partsSums(ls) 
                            var result = [0],
                            i = ls.length;

                            while (i--)
                            result.unshift(ls[i] + result[0]);

                            return result;


                            console.log(partsSums([0, 1, 3, 6, 10]));
                            console.log(partsSums([]));

                            .as-console-wrapper max-height: 100% !important; top: 0; 





                            function partsSums(ls) 
                            var result = [0],
                            l = 0,
                            i = ls.length;

                            while (i--) result.push(l += ls[i]);
                            return result.reverse();


                            console.log(partsSums([0, 1, 3, 6, 10]));
                            console.log(partsSums([]));

                            .as-console-wrapper max-height: 100% !important; top: 0; 





                            function partsSums(ls) 
                            var result = [0],
                            l = 0,
                            i = ls.length;

                            while (i--) result.push(l += ls[i]);
                            return result.reverse();


                            console.log(partsSums([0, 1, 3, 6, 10]));
                            console.log(partsSums([]));

                            .as-console-wrapper max-height: 100% !important; top: 0; 






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited 7 hours ago

























                            answered 7 hours ago









                            Nina ScholzNina Scholz

                            212k16 gold badges127 silver badges192 bronze badges




                            212k16 gold badges127 silver badges192 bronze badges



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56739270%2fsum-of-parts-of-an-array-javascript%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                                Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                                François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480