Nishanth Matha Nishanth Matha - 1 year ago 53
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,


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?

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

Answer Source

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) {
    } else {
      result[result.length - 1].push(element);
    return result;
  }, [[]]);

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