arrays - How to create sublists from a single list in JavaScript using a delimiter -


essentially want port solution for: python spliting list based on delimiter word javascript.

given: var example = ['a', 'word', 'b' , 'c' , 'word' , 'd'];

if delimiter of word provided generate:

var result = [['a'], ['word','b','c'],['word','d']];

is there alternative looping through list this?

the best approach here first write down algorithm, without getting specific code. called pseudo-code. have tried writing some? here's example:

  1. start off empty result of form [[]]. inner array call subarray.

  2. look @ next word in input. if it's 'word', add new subarray result , make current subarray.

  3. add word current subarray.

  4. repeat until input empty.

this type of algorithm, looping on array, , building kind of result, reduce designed for. can transform pseudo-code above directly js follows:

function split(array) {   var subarray = [];                // subarray adding elts    return array.reduce(              // loop on array     function(result, elt) {         // , each element       if (elt === 'word')           // if word, then...         result.push(subarray = []); // start new subarray , add result       subarray.push(elt);           // add current element subarray       return result;                // , return updated result     },      [subarray]);                    // start off array single subarray } 

using generators

if working in es6 environment, use es6 generators:

function* group(array) {   var subarray = [];    (var elt of array) {     if (elt === 'word') {         yield subarray;          subarray = [];      }     subarray.push(elt);   }    yield subarray; } 

here, array can iterable, since using for..of values.

now can print out subarrays by

for (grp of group(example)) console.log(grp); 

or create array of groups:

array.from(group(examples)) 

is there alternative looping through list this?

someone going have loop, or library routine. in first case, reduce doing looping; in es6 code, generator.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -