JS – How to dynamically split an array?

  • A+
Category:Languages

I have an array of strings, sort of like this:

["x", "foo", "y", "bar", "baz", "z", "0"] 

And I need to split the array for every X, Y, and Z or other special keywords there are.

I've tried to split arrays with [x,y,z].split(y), but I'm pretty sure split() is only for strings.

The keywords (x, y, and z) have to be the first ones in the array. How can I do this?

This is what I'm trying to get:

[     ["x", "foo"],     ["y", "bar", "baz"],     ["z", "0"] ] 

 


You could take an array and a closure over the index for the key strings and push an empty array if a key is found.

var array = ["x", "foo", "y", "bar", "baz", "z", "0"],     keys = ["x", "y", "z"],     result = array.reduce((i => (r, s) => {         if (s === keys[i]) {             r.push([]);             i++;         }         r[r.length - 1].push(s);         return r;     })(0), []);  console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: