1

How would you go about splitting an array at the word 'split' and creating smaller sub arrays out of them?

This is what my array looks like right now (but much longer):

const myArray = ['abc', 'xyz', 123, 'split', 'efg', 'hij', 456, 'split'];

This is what I would like it to look like:

const newArray =[['abc', 'xyz', 123], ['efg', 'hij', 456]];

If it helps at all I also have the indexes of the words 'split' in an array like this:

const splitIndex = [3, 7];
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35

2 Answers2

3

You could iterate splitIndex and slice the array until this index.

const
    data = ['abc', 'xyz', 123, 'split', 'efg', 'hij', 456, 'split'],
    splitIndex = [3, 7],
    result = [];

let i = 0;

for (const j of splitIndex) {
    result.push(data.slice(i, j));
    i = j + 1;
}

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0
const myArr = ['abc', 'xyz', 123, 'split', 'efg', 'hij', 456, 'split'];

const foo = (arr, key) => {
    let temp = [];
    const result = [];
    arr.forEach(v => {
        if (v !== key) {
            temp.push(v);
        } else {
            result.push(temp);
            temp = [];
        }
    })
    return result;
}
console.log(foo(myArr, 'split'));

output:

[ [ 'abc', 'xyz', 123 ], [ 'efg', 'hij', 456 ] ]
zitzennuggler
  • 106
  • 1
  • 6