Home > Enterprise >  How to find some letter in main array, and insert that elements in new array with for loop
How to find some letter in main array, and insert that elements in new array with for loop

Time:01-29

How to find the letter a, and insert elements with that letter in a temporary array?

function letterA (fruits){
    const tempArray = [];
    for (i = 0; i < fruits.length; i  ) {
        if (fruits.includes('a'))  {
           fruits.push(tempArray[i]);
        } 
        if (tempArray.length) {
            return tempArray;
        } else {
            console.log ("No elements with character 'a' found");
        }
    }
} 

letterA(fruits);

Please help

CodePudding user response:

You can use the filter method:

const fruits = ['banana', 'mango', 'apple', 'kiwi', 'lemons', 'limes'];
const filtered = fruits.filter(fruit => fruit.includes('a'))
console.log(filtered)

CodePudding user response:

This is a fix of your code using for loop. The if statement must check if fruits[i] includes 'a', then push to tempArray if true. Then checks if the tempArray has any elements and if so, it returns the tempArray. If not, it returns the string "No elements with character 'a' found".

const fruits = ['banana', 'mango', 'apple', 'kiwi', 'lemons', 'limes'];

function letterA (fruits){
    const tempArray = [];
    for (let i = 0; i < fruits.length; i  ) {
        if (fruits[i].includes('a'))  {
           tempArray.push(fruits[i]);
        } 
    }
    if (tempArray.length) {
        return tempArray;
    } else {
        return "No elements with character 'a' found";
    }
} 

let result = letterA(fruits);
console.log(result)

CodePudding user response:

here is the solution with for - of loop:

  const fruits = ['banana', 'mango', 'apple', 'kiwi', 'lemons', 'limes'];
  const result = [];
  for (const item of fruits) {
    if(item.includes('a')){
     result.push(item);
   }
 }

console.log(result)
  • Related