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.

Fansly
  • 29
  • 5
  • 4
    Take a few minutes to read through [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** – charlietfl Aug 08 '18 at 18:47
  • Possible duplicate of [Split Javascript array elements into chunks at designated indexes](https://stackoverflow.com/questions/47025900/split-javascript-array-elements-into-chunks-at-designated-indexes) – Sebastian Simon Aug 08 '18 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. – Damon Aug 08 '18 at 19:20
  • @Damon you are right. Sorry for the confusion. – Fansly Aug 08 '18 at 19:22

2 Answers2

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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;
}, [])
bombyx mori
  • 401
  • 3
  • 4