hibiya
hibiya

Reputation: 116

split Array with value - like String.split

In short, like this:

> l = ['asdf', '<br>', 'lorem', 'ipsum', '<hr>', 'dollar', 'sit', 'amex']
> l.split(/<.+>/)
[
  [ 'asdf' ] ,
  [ 'lorem', 'ipsum' ] ,
  [ 'dollar', 'sit', 'amex' ]
]

I wrote join-and-split one, but it seem slow with large array.

Is there any better solutions? indexOf()?

Upvotes: 1

Views: 57

Answers (1)

tckmn
tckmn

Reputation: 59273

A simple loop would do:

var result = [[]];
for (var i = 0; i < l.length; ++i) {
    if (/^<.+>$/.test(l[i]) {
        // start a new inner array
        result.push([]);
    } else {
        // append to the current inner array
        result[result.length-1].push(l[i]);
    }
}

Upvotes: 5

Related Questions