Sum of Parts of An Array - JavaScriptHow do JavaScript closures work?How do I remove a property from a...
Is there a way for presidents to legally extend their terms beyond the maximum of four years?
3D nonogram, beginner's edition
Wrong corporate name on employment agreement
Can you sign using a digital signature itself?
Should I share with a new service provider a bill from its competitor?
Can a Federation colony become a member world?
Spicket or spigot?
Why was Mal so quick to drop Bester in favour of Kaylee?
I hit a pipe with a mower and now it won't turn
How was film developed in the late 1920s?
Is there reliable evidence that depleted uranium from the 1999 NATO bombing is causing cancer in Serbia?
How can I reduce the sound of rain on a range hood vent?
Meaning of もてり and use of が
What does Mildred mean by this line in Three Billboards Outside Ebbing, Missouri?
How can my story take place on Earth without referring to our existing cities and countries?
What's the easiest way for a whole party to be able to communicate with a creature that doesn't know Common?
Does the Pi 4 resolve the Ethernet+USB bottleneck issue of past versions?
What is the difference between x RadToDeg cos x div and COSC?
When are digital copies of Switch games made available to play?
Mean Value Theorem: Continuous or Defined?
Why isn’t the tax system continuous rather than bracketed?
Can the UK Prime Minister immediately withdraw the country from the EU without backing from parliament?
Reverse of diffraction
Why are there so many religions and gods?
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;
}
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 ]
javascript arrays sum reduce
|
show 10 more comments
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 ]
javascript arrays sum reduce
don't you think you should be solving it yourself?
– Arpit Pandey
11 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
11 hours ago
Cant you just push 0 after the loop?
– Kobe
11 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
11 hours ago
1
BINGO! But consider the iterator point too.
– Randy Casburn
11 hours ago
|
show 10 more comments
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 ]
javascript arrays sum reduce
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
javascript arrays sum reduce
edited 11 hours ago
HappyHands31
asked 11 hours ago
HappyHands31HappyHands31
1,3903 gold badges22 silver badges41 bronze badges
1,3903 gold badges22 silver badges41 bronze badges
don't you think you should be solving it yourself?
– Arpit Pandey
11 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
11 hours ago
Cant you just push 0 after the loop?
– Kobe
11 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
11 hours ago
1
BINGO! But consider the iterator point too.
– Randy Casburn
11 hours ago
|
show 10 more comments
don't you think you should be solving it yourself?
– Arpit Pandey
11 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
11 hours ago
Cant you just push 0 after the loop?
– Kobe
11 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
11 hours ago
1
BINGO! But consider the iterator point too.
– Randy Casburn
11 hours ago
don't you think you should be solving it yourself?
– Arpit Pandey
11 hours ago
don't you think you should be solving it yourself?
– Arpit Pandey
11 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
11 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
11 hours ago
Cant you just push 0 after the loop?
– Kobe
11 hours ago
Cant you just push 0 after the loop?
– Kobe
11 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
11 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
11 hours ago
1
1
BINGO! But consider the iterator point too.
– Randy Casburn
11 hours ago
BINGO! But consider the iterator point too.
– Randy Casburn
11 hours ago
|
show 10 more comments
6 Answers
6
active
oldest
votes
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))
It works. There are some things about it that I don't understand. What is( O(n^2) )
? XOR, right?
– HappyHands31
11 hours ago
O(n²)
means that the number of calculations required grows exponentially as the length of your array grows. Thereduce
needs to look at every element in the array and you do that for every element in the array.
– Mark Meyer
11 hours ago
1
@NinaScholz Are you talking about the initialreduce()
? At least on chrome the overhead of the initial sum is much smaller than the penalty forunshift()
in my tests.
– Mark Meyer
10 hours ago
1
So, to break this down a bit more, we have the first sum as20
, then within the for-loop, we create the "result" array, initializing it to20
. Then we subtractls[i - 1]
from sum. So the first sum to get pushed into the result array from the for-loop will also be20
, becausels[i - 1]
in this case is0
. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.
– HappyHands31
10 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
3 hours ago
|
show 1 more comment
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]));
1
That is very clever yet simple. Thx.
– HappyHands31
10 hours ago
You could also doresult.unshift(ls[i] + result[0])
and avoidreverse
.
– georg
9 hours ago
1
@georgunshift
doesn't pass the test because it is slower thanpush+reverse
– Fraction
9 hours ago
add a comment |
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 || len + 1).reduce((a, n) => a + n, 0))
}
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]));
add a comment |
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]));
add a comment |
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]));
I like this also - can you please help me understand how theif(!ls.length) return [0]
gets added to the end of the returned array? There aren't any loops that are reducing the length ofls
?
– HappyHands31
10 hours ago
add a comment |
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; }
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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))
It works. There are some things about it that I don't understand. What is( O(n^2) )
? XOR, right?
– HappyHands31
11 hours ago
O(n²)
means that the number of calculations required grows exponentially as the length of your array grows. Thereduce
needs to look at every element in the array and you do that for every element in the array.
– Mark Meyer
11 hours ago
1
@NinaScholz Are you talking about the initialreduce()
? At least on chrome the overhead of the initial sum is much smaller than the penalty forunshift()
in my tests.
– Mark Meyer
10 hours ago
1
So, to break this down a bit more, we have the first sum as20
, then within the for-loop, we create the "result" array, initializing it to20
. Then we subtractls[i - 1]
from sum. So the first sum to get pushed into the result array from the for-loop will also be20
, becausels[i - 1]
in this case is0
. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.
– HappyHands31
10 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
3 hours ago
|
show 1 more comment
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))
It works. There are some things about it that I don't understand. What is( O(n^2) )
? XOR, right?
– HappyHands31
11 hours ago
O(n²)
means that the number of calculations required grows exponentially as the length of your array grows. Thereduce
needs to look at every element in the array and you do that for every element in the array.
– Mark Meyer
11 hours ago
1
@NinaScholz Are you talking about the initialreduce()
? At least on chrome the overhead of the initial sum is much smaller than the penalty forunshift()
in my tests.
– Mark Meyer
10 hours ago
1
So, to break this down a bit more, we have the first sum as20
, then within the for-loop, we create the "result" array, initializing it to20
. Then we subtractls[i - 1]
from sum. So the first sum to get pushed into the result array from the for-loop will also be20
, becausels[i - 1]
in this case is0
. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.
– HappyHands31
10 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
3 hours ago
|
show 1 more comment
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))
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))
edited 11 hours ago
answered 11 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
11 hours ago
O(n²)
means that the number of calculations required grows exponentially as the length of your array grows. Thereduce
needs to look at every element in the array and you do that for every element in the array.
– Mark Meyer
11 hours ago
1
@NinaScholz Are you talking about the initialreduce()
? At least on chrome the overhead of the initial sum is much smaller than the penalty forunshift()
in my tests.
– Mark Meyer
10 hours ago
1
So, to break this down a bit more, we have the first sum as20
, then within the for-loop, we create the "result" array, initializing it to20
. Then we subtractls[i - 1]
from sum. So the first sum to get pushed into the result array from the for-loop will also be20
, becausels[i - 1]
in this case is0
. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.
– HappyHands31
10 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
3 hours ago
|
show 1 more comment
It works. There are some things about it that I don't understand. What is( O(n^2) )
? XOR, right?
– HappyHands31
11 hours ago
O(n²)
means that the number of calculations required grows exponentially as the length of your array grows. Thereduce
needs to look at every element in the array and you do that for every element in the array.
– Mark Meyer
11 hours ago
1
@NinaScholz Are you talking about the initialreduce()
? At least on chrome the overhead of the initial sum is much smaller than the penalty forunshift()
in my tests.
– Mark Meyer
10 hours ago
1
So, to break this down a bit more, we have the first sum as20
, then within the for-loop, we create the "result" array, initializing it to20
. Then we subtractls[i - 1]
from sum. So the first sum to get pushed into the result array from the for-loop will also be20
, becausels[i - 1]
in this case is0
. Then 20 - 1, then 19 - 3, etc. Makes sense - thank you.
– HappyHands31
10 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
3 hours ago
It works. There are some things about it that I don't understand. What is
( O(n^2) )
? XOR, right?– HappyHands31
11 hours ago
It works. There are some things about it that I don't understand. What is
( O(n^2) )
? XOR, right?– HappyHands31
11 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
11 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
11 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
10 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
10 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
10 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
10 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
3 hours 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
3 hours ago
|
show 1 more comment
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]));
1
That is very clever yet simple. Thx.
– HappyHands31
10 hours ago
You could also doresult.unshift(ls[i] + result[0])
and avoidreverse
.
– georg
9 hours ago
1
@georgunshift
doesn't pass the test because it is slower thanpush+reverse
– Fraction
9 hours ago
add a comment |
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]));
1
That is very clever yet simple. Thx.
– HappyHands31
10 hours ago
You could also doresult.unshift(ls[i] + result[0])
and avoidreverse
.
– georg
9 hours ago
1
@georgunshift
doesn't pass the test because it is slower thanpush+reverse
– Fraction
9 hours ago
add a comment |
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]));
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]));
edited 10 hours ago
answered 10 hours ago
FractionFraction
1,8332 silver badges16 bronze badges
1,8332 silver badges16 bronze badges
1
That is very clever yet simple. Thx.
– HappyHands31
10 hours ago
You could also doresult.unshift(ls[i] + result[0])
and avoidreverse
.
– georg
9 hours ago
1
@georgunshift
doesn't pass the test because it is slower thanpush+reverse
– Fraction
9 hours ago
add a comment |
1
That is very clever yet simple. Thx.
– HappyHands31
10 hours ago
You could also doresult.unshift(ls[i] + result[0])
and avoidreverse
.
– georg
9 hours ago
1
@georgunshift
doesn't pass the test because it is slower thanpush+reverse
– Fraction
9 hours ago
1
1
That is very clever yet simple. Thx.
– HappyHands31
10 hours ago
That is very clever yet simple. Thx.
– HappyHands31
10 hours ago
You could also do
result.unshift(ls[i] + result[0])
and avoid reverse
.– georg
9 hours ago
You could also do
result.unshift(ls[i] + result[0])
and avoid reverse
.– georg
9 hours ago
1
1
@georg
unshift
doesn't pass the test because it is slower than push+reverse
– Fraction
9 hours ago
@georg
unshift
doesn't pass the test because it is slower than push+reverse
– Fraction
9 hours ago
add a comment |
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 || len + 1).reduce((a, n) => a + n, 0))
}
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]));
add a comment |
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 || len + 1).reduce((a, n) => a + n, 0))
}
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]));
add a comment |
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 || len + 1).reduce((a, n) => a + n, 0))
}
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]));
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 || len + 1).reduce((a, n) => a + n, 0))
}
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 || len + 1).reduce((a, n) => a + n, 0))
}
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 || len + 1).reduce((a, n) => a + n, 0))
}
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]));
edited 11 hours ago
answered 11 hours ago
Nenad VracarNenad Vracar
76.6k12 gold badges65 silver badges88 bronze badges
76.6k12 gold badges65 silver badges88 bronze badges
add a comment |
add a comment |
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]));
add a comment |
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]));
add a comment |
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]));
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]));
answered 10 hours ago
Elma CherbElma Cherb
1961 silver badge10 bronze badges
1961 silver badge10 bronze badges
add a comment |
add a comment |
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]));
I like this also - can you please help me understand how theif(!ls.length) return [0]
gets added to the end of the returned array? There aren't any loops that are reducing the length ofls
?
– HappyHands31
10 hours ago
add a comment |
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]));
I like this also - can you please help me understand how theif(!ls.length) return [0]
gets added to the end of the returned array? There aren't any loops that are reducing the length ofls
?
– HappyHands31
10 hours ago
add a comment |
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]));
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]));
answered 10 hours ago
Alexandre FradetteAlexandre Fradette
799 bronze badges
799 bronze badges
I like this also - can you please help me understand how theif(!ls.length) return [0]
gets added to the end of the returned array? There aren't any loops that are reducing the length ofls
?
– HappyHands31
10 hours ago
add a comment |
I like this also - can you please help me understand how theif(!ls.length) return [0]
gets added to the end of the returned array? There aren't any loops that are reducing the length ofls
?
– HappyHands31
10 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
10 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
10 hours ago
add a comment |
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; }
add a comment |
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; }
add a comment |
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; }
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; }
edited 10 hours ago
answered 11 hours ago
Nina ScholzNina Scholz
212k16 gold badges127 silver badges192 bronze badges
212k16 gold badges127 silver badges192 bronze badges
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
don't you think you should be solving it yourself?
– Arpit Pandey
11 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
11 hours ago
Cant you just push 0 after the loop?
– Kobe
11 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
11 hours ago
1
BINGO! But consider the iterator point too.
– Randy Casburn
11 hours ago