javascriptarraysfor-loop

returning two arrays in one array that contain names with a certain letter and names without the stated letter


I'm doing for-loop practice and can only use for loops to iterate over the arrays and strings in the problems I'm working. QUESTION:Return and array of 2 arrays // (1 - an array of names that contain "a" in name, 2 - an array of names that don't have 'a' in name)

I know how to push the names containing the letter 'a' to an array but the names that don't contain the letter a, are being pushed into the array as many times as it's being iterated over, how can I have the array of names that doesn't contain the letter 'a' only contain the name once and not as many times as its iterated over I know the issue lies somewhere is me having the for loop nested I think but I just cant see it, any tips or advice are welcome !

const arr1 = ['susan', 'meghan', 'timmy', 'tommy', 'thomas'];

function itsSomething(array) {
  let bothArrays = [];
  let withA = [];
  let withoutA = [];
  for (let i = 0; i < array.length; i++) {
    let name = array[i];
    for (let x = 0; x < name.length; x++) {
      if (name[x] == 'a') {
        withA.push(name)
      } else {
        withoutA.push(name)
      }
    }
  }
  bothArrays.push(withA, withoutA);
  return bothArrays
}

console.log(itsSomething(arr1))


Solution

  • There are two problems with your code:

    1. Once you find an a you should break out of the loop. Otherwise if the word has multiple a you'll push it to withA multiple times.
    2. You're pushing to withoutA whenever you find a non-a character, but there could still be an a later in the string. You have to wait until the end of the word to know if it had an a in it. Use a flag variable to hold this information.

    const arr1 = ['susan', 'meghan', 'timmy', 'tommy', 'thomas'];
    
    function itsSomething(array) {
      let withA = [];
      let withoutA = [];
      for (let i = 0; i < array.length; i++) {
        let name = array[i];
        let foundA = false;
        for (let x = 0; x < name.length; x++) {
          if (name[x] == 'a') {
            withA.push(name);
            foundA = true;
            break;
          }
        }
        if (!foundA) {
          withoutA.push(name)
        }
      }
      return [withA, withoutA];
    }
    
    console.log(itsSomething(arr1))

    There's no need for the bothArrays variable. You can simply create that array when you're returning the two arrays.