Home > Net >  How to replace multiple caracters in array? - Javascript
How to replace multiple caracters in array? - Javascript

Time:02-12

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:

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

How is the best way to do it?

CodePudding user response:

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

CodePudding user response:

Use a built in function replaceAll(), it is faster and you can replace any thing with this. I use string manipulations like this in real world projects

let array={
     "name": "Juan",
     "result": [
     [2,1,2],
     [1,0,2],
     [0,2,1]
     ]
    }
for(var i = 0; i < array.result.length; i  )
{
    console.log(array.result[i])
    array.result[i] = array.result[i].toString().replaceAll('2', 'a');
    array.result[i] = array.result[i].toString().replaceAll('1', 'b');
    array.result[i] = array.result[i].toString().replaceAll('0', ' ');
    console.log(array.result[i])

}
console.log(array.result)
  • Related