how to find how many items need to sum to get given sum in array javascript

I have array

var array = [4,2,6,8,1,6,5,2];
var samNeeded = 20;

as above i need to get how many items need to sum from start of the array to get sum needed

example needed output

var output = [4,2,6,8] 

as first four items need to sum up to get the total 20

64 thoughts on “how to find how many items need to sum to get given sum in array javascript”

  1. Here is my solution:

    const array = [4, 2, 6, 8, 1, 6, 5, 2];
    const sumNeeded = 20;
    let auxSum = 0;
    const res = [];
    for (let i = 0; i < array.length; i++) {
      if (auxSum >= sumNeeded) break;
      auxSum += array[i];
  2. Not sure this is the best approach, but it works for your example:

    const array = [4,2,6,8,1,6,5,2];
    const samNeeded = 20;
    let sum = 0;
    const result = [];
    // as long as array still has items and we haven't reached the target sum…
    while (array.length && sum < samNeeded) {
      result.push(array.shift()); // consume the next item of the input array
      sum += result[result.length - 1]; // add it to sum as we go.
    // it's not clear from your question whether you need the number of items…
    // or the items themselves:
  3. You could use Array#reduce.

    var array = [4,2,6,8,1,6,5,2];
    var sumNeeded = 20;
    let [res] = array.reduce(([res, sum],curr)=>
        [res.concat(sum >= sumNeeded ? []: curr), sum + (sum >= sumNeeded ? 0: curr)],
        [[], 0]);
  4. Hey just wanted to give you a quick heads up. The text in your content seem
    to be running off the screen in Firefox. I’m not sure if this is a format
    issue or something to do with browser compatibility but I figured I’d post to let you know.
    The style and design look great though! Hope you get the problem fixed
    soon. Kudos


Leave a Comment