Search code examples
javascriptarraysgrouping

Split array based on element contents?


Let's say my elements look like this:

const words = [
 'duck foo bar',
 'duck',
 'duck bing ',
 'bing',
 'Bloop#12 goose',
 'duck 12',
 'duck goose',
  ...
]

What I'd like is to split this into chunks where 'goose' is the final element in a chunk:

const words = [
 [
   'duck foo bar',
   'duck',
   'duck bing',
   'bing',
   'Bloop#12 goose',
 ], 
 [
   'duck 12',
   'duck goose',
 ], 
 [
  ...
 ],
];

There's no regularity to how many elements precede a 'goose', nor what is in each element except that 1) goose is always the last part of an element, and 2) goose never appears in any other element besides the one I want a chunk to end on (i.e. I never get 'goose foo', but I might get 'duck goose')


Solution

  • You could reduce the array and have a look to the previous string and add an array to the result set for a new group.

    const
        words = ['duck foo bar', 'duck', 'duck bing ', 'bing', 'Bloop#12 goose', 'duck 12', 'duck goose'],
        separator = 'goose',
        groups = words.reduce((r, s, i, a) => {
            if (!i || a[i - 1].includes(separator)) r.push([]);
            r[r.length - 1].push(s);
            return r;
        }, []);
    
    console.log(groups);
    .as-console-wrapper { max-height: 100% !important; top: 0; }