Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to split array into subarrays that sum the elements <= N in JavaScript

1 Answer

0 votes
const splitArray = (arr, N) => {
    return arr.reduce((acc, val, i) => {
        let { sum, result } = acc;
        if (i === 0) {
            return { sum: val, result:[[val]] };
        }
        if (sum + val <= N){
            result[result.length - 1].push(val);
            sum += val;
        } else {
            result.push([val]);
            sum = val;
        }
        return { sum, result };
    }, {
      sum: 0,
      result: []
   }).result;
};

const arr = [2, 3, 1, 4, 5, 1, 2, 3, 5, 2, 3, 3, 2, 1];

console.log(splitArray(arr, 7));




/*
run:

[[2, 3, 1], [4], [5, 1], [2, 3], [5, 2], [3, 3], [2, 1]]

*/

 



answered Nov 8, 2022 by avibootz
...