Nishanth Matha Nishanth Matha - 6 months ago 8
Javascript Question

split array at the element which matches regex

I have an array like:

var a= ['--test--','some','someOther','--ts','som','someOthe','--t','so','someOth']


I want to split this into 3 arrays ie,

['--test--','some','someOther']
['--ts','som','someOthe']
['--t','so','someOth']


So essentially I want to split it at the char which matches the condition
str.indexOf('--') > -1


what's the most efficient way to do it?

P.S
: I got it done with a gigantic code and weird logic, but I'm looking for a clean way to do this.

Answer

var a = ['--test--', 'some', 'someOther', '--ts', 'som', 'someOthe', '--t', 'so', 'someOth'];

function split(array, pattern) {
  return array.reduce(function(result, element, index) {
    if (pattern.test(element) && index) {
      result.push([element]);
    } else {
      result[result.length - 1].push(element);
    }
    return result;
  }, [[]]);
}

console.log(split(a, /--/));
console.log(split([], /--/));
console.log(split(['some', '--test--'], /--/));