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

Time:01-18

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

CodePudding user response:

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

CodePudding user response:

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 ] ]
  •  Tags:  
  • Related