0

I'm writing a function without the use of any JS built-in functions. This function accepts an array ['z','C',2,115,30] and then creates a new array with ascii values of chars in that first array plus the normal numbers that were there previously, so: [127, 67, 2, 115,30]. The problem I'm having is that I cannot properly get the numbers from the 1st array into the second array.

So far I can get the new array to [127,67,2,1,1,5,3,0]. So the chars ascii value is being inputted into the new array properly, but while iterating through the numbers it puts each digit of a number and then a comma into the array when i just want the whole number to be inputted instead of each digit.

function func(x){
    var str = '';
    var arr = [];
    for(var i=0; i<x.length;i++){
        str += x[i]
    }
    for(var j=0; j<str.length;j++){
        if(isNaN(str[j])){
            arr += str.charCodeAt(j) + ', ';
        }
        else if(!isNaN(str[j])){
            arr += str[j] + ', ';
        }
    } print(arr)

}

func(['z','C',2,115,30])

I expect output of [122, 67, 2, 115, 30], current output is [122, 67, 2, 1, 1, 5, 3, 0,]

3
  • The problem is the approach of turning the source array into a string in the first place. There's no reason to do that, and that's what's causing your problems. Iterate through the source array and determine what the type of each element is with typeof not isNaN() because isNaN() doesn't mean what one might think it means. Commented Jul 29, 2019 at 22:08
  • 1
    Also in general if (something) else if (!something) is pointless. If something is not true then !something is true, by definition. Commented Jul 29, 2019 at 22:09
  • @Pointy i cant get the ascii value of char unless its in a string using charCodeAt() Commented Jul 30, 2019 at 4:13

1 Answer 1

2

Don't combine into one string - instead, use a simple for loop:

 

function func(x) {
  var arr = [];
  for (let i = 0; i < x.length; i++) {
if (typeof x[i] == "string") arr[arr.length] = (x[i].charCodeAt(0);
else arr[arr.length] = x[i];
  }
  console.log(arr);
}

func(['z','C',2,115,30]);

Using array methods is much simpler though:

 

function func(x) {
  var arr = x.map(e => typeof e == "string" ? e.charCodeAt(0) : e);
  console.log(arr);
}

func(['z','C',2,115,30]);

Sign up to request clarification or add additional context in comments.

2 Comments

Can't use Js built in functions so .push and .map would give me 0 points in this case.
Fixed @Tiago - you can ignore the second one for your submission, it's just my take. The first one doesn't use any methods now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.