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

63
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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