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

60
Vistas
javascript foreach in a matrix

I have a matrix consisting in 0s, 1s and an "X" and I'm trying to use the "forEach()" method in order to find the "X" and replace it with another value. How would I exactly do that?

let a=new Array
for(int i=0;i<=5;i++) {
  a[i]=new Array
  for(int j=0;j<=5;j++) {
    a[i][j]=Math.round(Math.random())
  }
}
a[3][2]="X" //the indexes are random values

for(int i=0;i<=5;i++) {
  for(int j=0;i<=5;j++) {
    if(a[i][j]=="X") {
      a[i][j]="found"
      break
    }
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

let matrix1 = [
[0, 1, 0, 1, 1],
[1, 0, 1, 1, 1],
[0, 1, 1, 0, 0],
[1, 0, 1, 0, 1],
[0, 1, 1, 'x', 1]
];

matrix1
    .forEach((element1, index1, array1) => { 
        element1.forEach((element2, index2, array2) => {
            if(array1[index1][index2] == 'x') {
                array1[index1][index2] = 'y';
            }
        });
    });

There may be other (and better solutions), but this should work. But I would recommend to stay with the two nested-for-loops.
For the forEach approach two lambda-functions have to be created and when they are called a context-switch happens (not sure about that, might be optimized/removed by the javascript interpreter). So the memory-footprint might be slightly higher and the performance probably lower. But for a 5x5 matrix nothing of that is important.
Plain for loops are also much more readable - at least for me ;)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Instead of doing it with forEach, I would be using for-of loop.

let matrix = [
  [0, 1, 0, "x", 1],
  [1, 0, 1, 1, 1],
  [0, "x", 1, 0, 0],
  ["x", 0, 1, 0, 1],
  [0, 1, 1, 0, 1]
];

for (const [i, row] of matrix.entries()) {
  for (const [j, element] of row.entries()) {
    if (element === "x") {
      matrix[i][j] = "Boom";
    }
  }
}

Final, output would be:

[
  [0, 1, 0, "Boom", 1],
  [1, 0, 1, 1, 1],
  [0, "Boom", 1, 0, 0],
  ["Boom", 0, 1, 0, 1],
  [0, 1, 1, 0, 1]
]
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