Home > Blockchain >  Substrings non repeating characters - For loop
Substrings non repeating characters - For loop

Time:03-26

I want to write a function that will return the substrings of non repeating characters within the main string.

function nonRepeating(str){
  let arrays = []
  let array = []

  for(let i = 0; i < str.length; i  ){
    if(!array.includes(str[i])){
      array.push(str[i])     
    }
    else {
      arrays.push(array.join(""))
      array = []
    }    
  }
    return arrays
}

 console.log(nonRepeating("example.com"))

My question is why am I getting only

['exampl']

instead of

['exampl', '.com']

CodePudding user response:

It is because else does not get executed after the last element . The code never reaches the else statement. You can improve the existing code by adding a 1 to increase the loop count.

    function nonRepeating(str) {
    let arrays = []
    let array = []

    for (let i = 0; i <= str.length 1 ; i  ) {
        console.log(array)
        if (!array.includes(str[i])) {
            array.push(str[i])
        }
        else {
            arrays.push(array.join(""));
            console.log('i am not called')
            array = []
        }
    }
    

    return arrays
}
It's still not optimal but works.

CodePudding user response:

Before returning arrays check to see if array has any data and push() it to arrays:

if( array.length ) {
    arrays.push( array.join("") );
}

function nonRepeating(str){
  let arrays = []
  let array = []

  for(let i = 0; i < str.length; i  ){
    if(!array.includes(str[i])){
      array.push(str[i])     
    }
    else {
      arrays.push(array.join(""))
      array = []
    }   
  }
  if( array.length ) {
    arrays.push( array.join("") );
  }
  return arrays
}

 console.log(nonRepeating("example.com"))

  • Related