skip to Main Content

I need to get the elements from an array that do not have the letter 'l' in them and push it to another array, just using the for loop. For this project no special methods are allowed. I can only use the push() and toLowerCase() methods.

The result I get is a list of all the names repeated multiple times.

var list =['sage', 'carolina', 'everly', 'carlos', 'frankie'];
var list1 =[];

for(let i in list){
  for(let j in list[i]){
//Get name without the 'l'
    if(list[i][j].toLowerCase() !== 'l'){
      list1.push(list[i]);
    }
  }
}
console.log(list1);

2

Answers


  1. A few notes to make:

    1. First check whole word if it contains the letter
    2. Outside that loop, push result so it gets only added once
    3. Better to check it has the letter then the reverse 🙂
    var list = ['sage', 'carolina', 'everly', 'carlos', 'frankie'];
    var result = [];
    
    for(let i in list){
      var hasL = false;
      // Check every letter
      for(let j in list[i]){
        if(list[i][j].toLowerCase() === 'l') {
          hasL = true;
          break;
        }
       }
      
      // If the condition (hasL) hasn't been met, push to result
      if (!hasL) {
        result.push(list[i]);
      }
    
    }
    
    console.log(result);
    Login or Signup to reply.
    1. In the inner loop check if at least one element has the letter
    2. If it has, add the item to the list in the outer loop
    const list = ['sage', 'carolina', 'everly', 'carlos', 'frankie'];
    const list1 = [];
    
    for (const str of list) {
      let hasLetter = false
      for (const char of str) {
        if (char.toLowerCase() === 'l') {
          hasLetter = true
          break
        }
      }
      if (!hasLetter) {
        list1.push(str)
      }
    }
    console.log(list1);

    Shorter version below:

    const list = ['sage', 'carolina', 'everly', 'carlos', 'frankie'];
    const list1 = list.filter(item => !/l/i.test(item))
    console.log(list1)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search