Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

101
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda