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

100
Visualizações
Split array elements dynamically

I have below scenarios to handle.

let data = [
    [ "ALISHA", "SUICA", "PASMO" ],
    [ "HARMONY" ],
    [ "OCTOPUS" ]
]

let data1 = [
    [ "ALISHA",  ],
    [ "HARMONY" ],
    [ "OCTOPUS", "SUICA", "PASMO" ]
]

For both of the above data, i want the result to look like this.

let result = [
    [ "ALISHA" ],
    [ "HARMONY" ],
    [ "OCTOPUS" ], 
    [ "SUICA" ],
    [ "PASMO" ]
]

Can someone please let me know how to achieve this. I tried the following but no success

let result = []
for (let i = 0; i < data.length; i++) {
    let split = data[i].split(",");  // just split once
    result.push(split[0]); // before the comma 
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

we will use forEach method on main array inside forEach we will use if condition if is array and length more than 1 will add another forEach method and push sub array to main array after that remove sub array look like that

let data = [
  ["ALISHA"],
  ["HARMONY"],
  ["OCTOPUS", "SUICA", "PASMO"]
]

data.forEach((cur, index) => {
  if (Array.isArray(cur) && cur.length > 1) {
    cur.forEach(cur => data.push([cur]))
    data.splice(index, 1);
  }
})

console.log(data)

about 4 years ago · Juan Pablo Isaza Relatório

0

Uses Array.reduce extract all elements, then convert to [string] by Array.map.

const data = [
    [ "ALISHA" ],
    [ "HARMONY" ],
    [ "OCTOPUS", "SUICA", "PASMO" ]
]

console.log(
  data.reduce((pre, cur) => [...pre, ...cur], []).map(item => [item])
  // data.reduce((pre, cur) => pre.concat(...cur), []).map(item => [item]) // different methods but same logic (uses Array.concat instead of spread operator)
)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use flat and map

const data = [["ALISHA"], ["HARMONY"], ["OCTOPUS", "SUICA", "PASMO"]];

const result = data.flat().map((a) => [a]);
console.log(result);

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