简体   繁体   中英

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() ?

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]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM