Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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];
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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 ] ]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!