0

My task is to write a function that changes a string to an integer. If the value is greater than zero, I have to save it in a new array, if it is not to be filtered, the same as the digits that are in the array. tab1 = ['d', 'e', 3, 'h', 11, -2, 'P'] This is the board. Generally, it is a change according to ASCII, but with a slight change because, for example, d is to be written as 3, i.e. from each result, additional 97 should be subtracted. Can anyone help me with this? I absolutely do not know how to go about it :( So far I have managed to create so much; /

var tab1=['d','e',3,'h',11,-2,'P'];
let tab2=[];
function convertStingToInt(){
    for (let i = 0; i < tab1.length; i++)
    tab2 = tab1.charCodeAt([i]);
}

console.log(tab2);

1 Answers1

0

Here's two versions that works properly – I prefer the last one (for readability).

P.S. You code has many mistakes to count so I'm not going to go through them unless you want me to.

var tab1=['d','e',3,'h',11,-2,'P'];

function convertStingToInt(arr){
    let tab2=[];
    for (let i = 0; i < arr.length; i++) {
        if (typeof arr[i] !== 'number') {
          var val = arr[i].charCodeAt(0);
        } else {
          var val = arr[i];
        }
        if (val > 0) tab2.push(val);
    }
    return tab2;
}

console.log(convertStingToInt(tab1)); // [100, 101, 3, 104, 11, 80]
var tab1=['d','e',3,'h',11,-2,'P'];

var tab2 = tab1.map(function(x) {
  if (typeof x !== 'number') {
    return x.charCodeAt(0);
  } else {
    return x;
  } 
}).filter(function(x) {
  if (x > 0) return true;
});

console.log(tab2); // [100, 101, 3, 104, 11, 80]
Khalid Ali
  • 1,224
  • 1
  • 8
  • 12