javascriptarraysmultidimensional-array

JS How to loop through an array and slice/create a new array at every empty element in the array?


I have an array like this:

['a 3', 'b', 'c 145', '', 'e', 'f 98', '', 'g 1', 'h', '', 'bla', 'bla']

I want to make columns by splitting at every '' so it would look like this:

[['a 3', 'b', 'c 145'], ['e', 'f 98'], ['g 1', 'h'], ['bla', 'bla']]

I've tried all kinds of things.


Solution

  • Here's an updated approach that uses reduce and starts a new array each time it encounters an element with value ''

    const arr = ['a3', 'b', 'c145', '', 'e', 'f98', '', 'g0', 'h', '', 'bla', 'bla'];
    let start = 0;
    const out = arr.reduce((p, c, i) => {
      const isLast = i === arr.length - 1;
      if (c === '' || isLast) {
         let end = isLast ? arr.length : i;
         p.push(arr.slice(start, end))
         start = i+1;
      }
      return p;
    }, []);
    console.log(out);