0

In javascript, how to split an array into chunks by breaks? For example,

var array = [0,1,2,3,4,5,6,7,8,9,12,13,15,20]
var breaks = [0,3.5,13]
somefunction(array, breaks) === [[0,1,2,3],[4,5,6,7,8,9,12],[13,15,20]]
// true

The value in breaks does not necessarily in the array.

4
  • 4
    Take a few minutes to read through How to Ask then add the code that you have tried. Stackoverflow is not a free code writing service. The objective is for others to help fix your code Commented Aug 8, 2018 at 18:47
  • Possible duplicate of Split Javascript array elements into chunks at designated indexes Commented Aug 8, 2018 at 18:47
  • I assume based on your output that breaks is referring to values not indices. Why does 4 get put in the second bin based on a 4.5 break? That would indicate to me that 4 should go into the first bin. Commented Aug 8, 2018 at 19:20
  • @Damon you are right. Sorry for the confusion. Commented Aug 8, 2018 at 19:22

2 Answers 2

0

Another version for reduce, using its optional arguments

breaks.reduce((acc, cur, idx, arr) => {
  acc.push(
    array.slice(
      array.indexOf(cur),
      arr[idx+1] ? array.indexOf(arr[idx+1]) : array.length
    )
  );
  return acc;
}, [])
Sign up to request clarification or add additional context in comments.

Comments

0

You could use an index for the break array and check the value while iterating array. For each found value add a new array.

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 15, 20],
    breaks = [0, 3.5, 13],
    index = 0,
    result = array.reduce((r, v) => {
        if (v >= breaks[index]) {
            r.push([]);
            ++index;
        }
        r[r.length - 1].push(v);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.