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?

What are good ways to spray paint a QR code on a footpath?

What's the safest way to inform a new user of their password on my web site?

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

What could a reptilian race tell by candling their eggs?

Do space suits measure "methane" levels or other biological gases?

How exactly is a normal force exerted, at the molecular level?

Different budgets within roommate group

Why are there so many religions and gods?

Is there a way for presidents to legally extend their terms beyond the maximum of four years?

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

How fast can a ship with rotating habitats be accelerated?

"Plugged in" or "Plugged in in"

How to fix a dry solder pin in BGA package?

Wrong corporate name on employment agreement

In the context of a differentiator circuit, what is a “current-sensing resistor”?

Can Access Fault Exceptions of the MC68040 caused by internal access faults occur in normal situations?

How did researchers use to find articles before the Internet and the computer era?

Do I have to roll to maintain concentration if a target other than me who is affected by my concentration spell takes damage?

Most importants new papers in computational complexity

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

Can the passive "être + verbe" sometimes mean the past?

How would an order of Monks that renounce their names communicate effectively?

Golf the smallest circle!

Does Anosov geodesic flow imply asphericity?



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
    9 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
    9 hours ago











  • Cant you just push 0 after the loop?

    – Kobe
    9 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
    9 hours ago






  • 1





    BINGO! But consider the iterator point too.

    – Randy Casburn
    9 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
    9 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
    9 hours ago











  • Cant you just push 0 after the loop?

    – Kobe
    9 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
    9 hours ago






  • 1





    BINGO! But consider the iterator point too.

    – Randy Casburn
    9 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 8 hours ago







HappyHands31

















asked 9 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
    9 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
    9 hours ago











  • Cant you just push 0 after the loop?

    – Kobe
    9 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
    9 hours ago






  • 1





    BINGO! But consider the iterator point too.

    – Randy Casburn
    9 hours ago

















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

    – Arpit Pandey
    9 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
    9 hours ago











  • Cant you just push 0 after the loop?

    – Kobe
    9 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
    9 hours ago






  • 1





    BINGO! But consider the iterator point too.

    – Randy Casburn
    9 hours ago
















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

– Arpit Pandey
9 hours ago





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

– Arpit Pandey
9 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
9 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
9 hours ago













Cant you just push 0 after the loop?

– Kobe
9 hours ago





Cant you just push 0 after the loop?

– Kobe
9 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
9 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
9 hours ago




1




1





BINGO! But consider the iterator point too.

– Randy Casburn
9 hours ago





BINGO! But consider the iterator point too.

– Randy Casburn
9 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
    8 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
    8 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
    8 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
    8 hours ago







  • 1





    @HappyHands31 per Mark Meyer's comment above, if you need to ask "What is ( O(n^2))" then you probably can benefit by being told explicitly this is called "Big-O" notation.

    – JimLohse
    1 hour 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
    7 hours ago











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

    – georg
    7 hours ago






  • 1





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

    – Fraction
    7 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--)
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
        8 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
          8 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
          8 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
          8 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
          8 hours ago







        • 1





          @HappyHands31 per Mark Meyer's comment above, if you need to ask "What is ( O(n^2))" then you probably can benefit by being told explicitly this is called "Big-O" notation.

          – JimLohse
          1 hour 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
          8 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
          8 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
          8 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
          8 hours ago







        • 1





          @HappyHands31 per Mark Meyer's comment above, if you need to ask "What is ( O(n^2))" then you probably can benefit by being told explicitly this is called "Big-O" notation.

          – JimLohse
          1 hour 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 8 hours ago

























        answered 8 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
          8 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
          8 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
          8 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
          8 hours ago







        • 1





          @HappyHands31 per Mark Meyer's comment above, if you need to ask "What is ( O(n^2))" then you probably can benefit by being told explicitly this is called "Big-O" notation.

          – JimLohse
          1 hour ago


















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

          – HappyHands31
          8 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
          8 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
          8 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
          8 hours ago







        • 1





          @HappyHands31 per Mark Meyer's comment above, if you need to ask "What is ( O(n^2))" then you probably can benefit by being told explicitly this is called "Big-O" notation.

          – JimLohse
          1 hour ago

















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

        – HappyHands31
        8 hours ago






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

        – HappyHands31
        8 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
        8 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
        8 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
        8 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
        8 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
        8 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
        8 hours ago





        1




        1





        @HappyHands31 per Mark Meyer's comment above, if you need to ask "What is ( O(n^2))" then you probably can benefit by being told explicitly this is called "Big-O" notation.

        – JimLohse
        1 hour ago






        @HappyHands31 per Mark Meyer's comment above, if you need to ask "What is ( O(n^2))" then you probably can benefit by being told explicitly this is called "Big-O" notation.

        – JimLohse
        1 hour 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
          7 hours ago











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

          – georg
          7 hours ago






        • 1





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

          – Fraction
          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
          7 hours ago











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

          – georg
          7 hours ago






        • 1





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

          – Fraction
          7 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 8 hours ago

























        answered 8 hours ago









        FractionFraction

        1,8702 silver badges16 bronze badges




        1,8702 silver badges16 bronze badges







        • 1





          That is very clever yet simple. Thx.

          – HappyHands31
          7 hours ago











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

          – georg
          7 hours ago






        • 1





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

          – Fraction
          7 hours ago












        • 1





          That is very clever yet simple. Thx.

          – HappyHands31
          7 hours ago











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

          – georg
          7 hours ago






        • 1





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

          – Fraction
          7 hours ago







        1




        1





        That is very clever yet simple. Thx.

        – HappyHands31
        7 hours ago





        That is very clever yet simple. Thx.

        – HappyHands31
        7 hours ago













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

        – georg
        7 hours ago





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

        – georg
        7 hours ago




        1




        1





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

        – Fraction
        7 hours ago





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

        – Fraction
        7 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--)
        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--)
          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--)
            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--)
            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--)
            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--)
            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 8 hours ago

























            answered 8 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 8 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
                          8 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
                          8 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 8 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
                          8 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
                          8 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
                        8 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
                        8 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 8 hours ago

























                            answered 8 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

                                The fall designs the understood secretary. Looking glass Science Shock Discovery Hot Everybody Loves Raymond Smile 곳 서비스 성실하다 Defas Kaloolon Definition: To combine or impregnate with sulphur or any of its compounds as to sulphurize caoutchouc in vulcanizing Flame colored Reason Useful Thin Help 갖다 유명하다 낙엽 장례식 Country Iron Definition: A fencer a gladiator one who exhibits his skill in the use of the sword Definition: The American black throated bunting Spiza Americana Nostalgic Needy Method to my madness 시키다 평가되다 전부 소설가 우아하다 Argument Tin Feeling Representative Gym Music Gaur Chicken 일쑤 코치 편 학생증 The harbor values the sugar. Vasagle Yammoe Enstatite Definition: Capable of being limited Road Neighborly Five Refer Built Kangaroo 비비다 Degree Release Bargain Horse 하루 형님 유교 석 동부 괴롭히다 경제력

                                Sahara Skak | Bilen | Luke uk diar | NawigatsjuunCommonskategorii: SaharaWikivoyage raisfeerer: Sahara26° N, 13° O

                                19. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу