Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
I want to split an array and splice it based on some pattern inside the array

Hello I couldn't figure out how to do this,

Let's say I have an array like this

main = [ "1","2","A","4","5","B","6","7","A","8","9","B","10"];

I want to get a new array with result

main2 = ["A","4","5","B","A","8","9","B"] 

and finally break them apart like the following;

main3 = ["A","4","5","B"]     
main4 = ["A","8","9","B"]

As you can see I am taking out the array items from A-B that happened twice.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could reduce the array into arrays, starting with a certain value and ending with another.

const
    start = 'A',
    end = 'B',
    data = ["1", "2", "A", "4", "5", "B", "6", "7", "A", "8", "9", "B", "10"],
    result = data.reduce((r, v) => {
        if (v === start) { r.push([v]); return r; }
        const last = r[r.length - 1];
        if (last?.length && last[last.length - 1] !== end) last.push(v);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Another approach

const
    start = 'A',
    end = 'B',
    data = ["1", "2", "A", "4", "5", "B", "6", "7", "A", "8", "9", "B", "10"],
    result = [];

let i = data.indexOf(start);

while (i !== -1) {
    let j = data.indexOf(end, i + 1);
    result.push(data.slice(i, ++j));
    i = data.indexOf(start, j);
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

Here's the old-school approach.

const main = ["1", "2", "A", "4", "5", "B", "6", "7", "A", "8", "9", "B", "10"];
const start = "A";
const end = "B";
let result = [];
let isCollecting = false;

main.forEach(item => {
  if (item === start) isCollecting = true;

  if (isCollecting) result.push(item);

  if (item === end) {
    console.log(result);
    result = [];
    isCollecting = false;
  }
});

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda