Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace multiple caracters in array? – Javascript

I am learning Javascript,
I want to replace some caracters of this array:

 let array={
     "name": Juan,
     "result": [
     [2,1,2],
     [1,0,2],
     [0,2,1]
     ]
    }

I would like to replace in this way "2" -> "a", "1" -> "b", "0" -> "";

Result should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 let array= {
     "name": Juan,
     "result": [
     [a,b,a],
     [b, ,a],
     [ ,a,b]
     ]
    }

How is the best way to do it?

>Solution :

Iterate over aray.result and replace each element. You can either use a nested for loop or a nested map.

let array = {
  "name": "Juan",
  "result": [
    [2, 1, 2],
    [1, 0, 2],
    [0, 2, 1]
  ]
};

array.result = array.result.map(row => row.map(el => {
  switch (el) {
    case 2: return 'a';
    case 1: return 'b';
    case 0: return '';
    default: return el;
  }
}));

console.log(array);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading