0

For example, I have a string "asdf123d6lkj006m90" and I need the following result [123, 6, 0, 0, 6, 90]. I tried:

let str = "asdf123d6lkj006m90"
let func = function(inputString){
    let outputArray = []
    let currentNumber = ""
    for(let element of inputString){
        if(Number(element)||element == 0){
            outputArray.push(Number(element))
        }
    }
    return(outputArray)
}
console.log(func(str))

But it returns [ 1, 2, 3, 6, 0, 0, 6, 9, 0 ] How do I receive the correct numbers?

1
  • That's because you're looking at 1 character at a time. I doesn't seem like you have an objective goal though. The 0s part is confusing, and that's not what a regex would return either. Commented Nov 15, 2022 at 19:39

1 Answer 1

1

You're looking at each character at a time, when you should be checking the next few as well.

const str = "asdf123d6lkj006m90";
console.log(numbers(str));

function numbers(str) {
  const nums = []; // create an array with the numbers
  for(let i = 0; i < str.length; i++) {
    // in your example you want preceding 0s to be their own number
    if(str[i] == 0) {
      nums.push(0);
      continue;
    }
    
    let current = ""; // add to our string
    while(!isNaN(str[i])) {
      // as long as the character can be converted to a number
      current += str[i++];
    }
    // if there were any numbers added
    if(current.length)
      nums.push(+current);
  }
  return nums;
}

And note, while this looks like O(n^2) because of the nested loop, it's actually still linear because the loops are traversing the same array and one picks up where the other left off.

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

2 Comments

Thank you! I'm just starting to learn JS and it's a bit difficult:) I appreciate your help
@Enedwaith no problem. I hope it helped you. (By the way, if it solved your problem, would you mind selecting it as such? Thanks!)

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.