0

I have an array like so

const arr = [3,6,9,12,18,21,24,27,33,36];

I want the array arr split into chunks at 12, 21 and 33. That is at the index 3, 5, and 8. I want to produce another array chunks looking like this..

const chunks = [[3,6,9,12],[18,21],[24,27,33],[36]];

The solutions I have seen here basically split arrays into 'n' chunks. Basically I want to split at arrays at several (specified) indexes.

I do not mind an underscore.js/lodash solution. Thanks

dtechplus
  • 579
  • 1
  • 6
  • 21
  • 1
    How is this question a duplicate of [split an array into two based on a index in javascript](https://stackoverflow.com/questions/6872630/split-an-array-into-two-based-on-a-index-in-javascript) ? The answers there address spliting an array into 2 albeit by index, mine into several parts. – dtechplus Oct 31 '17 at 06:52
  • It's not exact duplicate, but there is no way to split it in one operation as for example can be done for strings. Each part of the array has to be extracted separately in a loop. – Slai Nov 01 '17 at 15:02

4 Answers4

6

You could use reduceRight and decide which elements to split at. Since you’re providing the last values of a sub-array rather than the first ones, going from right to left is actually a bit easier, hence I use a reduceRight rather than a reduce.

Split by value

const arr = [3, 6, 9, 12, 18, 21, 24, 27, 33, 36],
  splitValues = [12, 21, 33],
  chunks = arr.reduceRight((result, value) => {
    result[0] = result[0] || [];

    if (splitValues.includes(value)) {
      result.unshift([value]);
    } else {
      result[0].unshift(value);
    }

    return result;
  }, []);

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

Split by index

const arr = [3, 6, 9, 12, 18, 21, 24, 27, 33, 36],
  splitIndexes = [3, 5, 8],
  chunks = arr.reduceRight((result, value, index) => {
    result[0] = result[0] || [];

    if (splitIndexes.includes(index)) {
      result.unshift([value]);
    } else {
      result[0].unshift(value);
    }

    return result;
  }, []);

console.log(chunks);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
3

const arr = [3,6,9,12,18,21,24,27,33,36];

// Important: this array gets mutated. Make a copy if that's not okay.
const inds = [3,5,8];

const chunked = arr.reduce((p, c, i) => { if (i-1 === inds[0]) { inds.shift(); p.push([]); } p[p.length-1].push(c); return p; }, [[]]);

console.log(chunked)
CRice
  • 29,968
  • 4
  • 57
  • 70
2

Here's an alternative way of doing it that I think is a bit clearer.

function chunkIt(arr, indexes) {
    const ret = [];
    let last = 0;

    indexes.forEach(i => {
        ret.push(arr.slice(last, i + 1));
        last = i + 1;
    });
    if (last < arr.length) {
        ret.push(arr.slice(last));
    }
    return ret;
}

console.log(chunkIt([3,6,9,12,18,21,24,27,33,36], [3,5,8]));
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
1

A bit "simplified" version with the reversed indexes, but splice modifies the source array:

arr = [3, 6, 9, 12, 18, 21, 24, 27, 33, 36]

chunks = [9, 6, 4, 0].map(i => arr.splice(i)).reverse()

console.log(JSON.stringify(chunks))

or slice can be used instead to preserve the source array:

arr = [3, 6, 9, 12, 18, 21, 24, 27, 33, 36], indexes = [0, 4, 6, 9]

chunks = indexes.map((e, i) => arr.slice(e, indexes[i + 1]))

console.log(JSON.stringify(chunks))
Slai
  • 22,144
  • 5
  • 45
  • 53