BennyLearnsCode
BennyLearnsCode

Reputation: 41

How to split an array into smaller arrays every time a specific value appears JavaScript?

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

Upvotes: 1

Views: 633

Answers (2)

zitzennuggler
zitzennuggler

Reputation: 106

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 ] ]

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

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

Upvotes: 3

Related Questions