Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

58
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!