The best approach here is to first write down the algorithm, without getting into specific code. Sometimes this is called pseudo-code. Have you tried writing some? Here's an example:
Start off with an empty result of the form [[]]
. The inner array we will call subarray
.
Look at the next word in the input. If it's 'WORD', then add a new subarray to the result and make it the current subarray.
Add the word to the current subarray.
Repeat until input is empty.
This type of algorithm, where we are looping over an array, and building up some kind of result, is exactly what reduce
was designed for. We can transform the pseudo-code above almost directly into JS as follows:
function split(array) {
var subarray = []; // subarray we are adding elts to
return array.reduce( // loop over the array
function(result, elt) { // and for each element
if (elt === 'WORD') // if it is word, then...
result.push(subarray = []); // start a new subarray and add to result
subarray.push(elt); // add the current element to the subarray
return result; // and return the updated result
},
[subarray]); // start off with an array with a single subarray
}
Using generators
If you are working in an ES6 environment, you could use ES6 generators:
function* group(array) {
var subarray = [];
for (var elt of array) {
if (elt === 'WORD') {
yield subarray;
subarray = [];
}
subarray.push(elt);
}
yield subarray;
}
Here, array
can actually be any iterable, since we are using for..of
to get its values.
Now you can print out your subarrays by
for (grp of group(example)) console.log(grp);
Or create an array of the groups:
Array.from(group(examples))
Is there an alternative to looping through the list to do this?
Someone is going to have to loop, be it you or some library routine. In the first case, it is reduce
doing the looping; in the ES6 code, it is the generator.