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

3 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];
      res.push(array[i]);
    }
    
    console.log(res);
    Reply
  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…
    console.log(result.length);
    
    // or the items themselves:
    console.log(result);
    Reply
  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]);
    console.log(res);
    Reply

Leave a Comment