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

135
Vistas
Array of string to array of array in Javascript

I'm wondering how to convert an array of strings

lines = ['101','010','110'];

to an array of arrays like this:

x = [
[1,0,1],
[0,1,0],
[1,1,0]'
]

I already tried

x = (lines.forEach(e => (e.split(''))))

and realized String.split doesnt mutate the current string. So my next step was to create a new array with these values.

x = new Array(lines.forEach(e => (e.split(''))))

My thoughts behind this line: The code should take an element (e) of the lines array and apply the split funtion to it. (which is does when i console.log() it.) BUT it doesnt apply it to the new array.

Maybe the problem is, that it doesn't loop through x but maybe i overlook another fact.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use .map(Number) on the split() result to convert them to a Number as expected

const lines = ['101','010','110'];
const res = lines.map(l => l.split('').map(Number));

console.log(res);

[
  [
    1,
    0,
    1
  ],
  [
    0,
    1,
    0
  ],
  [
    1,
    1,
    0
  ]
]

Regarding your forEach solution, since forEach does not return anything, x stays undefined

You could define an empty array, and push your split() into that empty array, but using map() is a more readable/clean solution.

For more information about map() vs forEach(), please take a look at this stackoverflow answer.

about 4 years ago · Juan Pablo Isaza Denunciar

0

As per @OstoneO's answer, Array#map() is the most appropriate method to use, hence it would be my first choice.

Array#forEach()'s return value is undefined because it's not designed to return a value; it is a loop and should be used as such:

const lines = ['101','010','110'];

const x = [];
lines.forEach( line => x.push( line.split('').map(n => +n) ) );

console.log( x );

about 4 years ago · Juan Pablo Isaza Denunciar

0

Using Array.prototype.reduce method,

 ['101','010','110'].reduce((acc,val,index)=>{
    acc[index] = [...val.split("").map((item)=>parseInt(item))];
    return acc;

}
,[]);
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