skip to Main Content

I am solving a question of JavaScript by using find method. I want to find the first and all elements of array that contain letter ‘e’.

const fruits = ['apple', 'banana', 'cherry', 'dates', 'fig']

How I solve:

const res = words.find((alpha) => alpha == words)

2

Answers


  1. I want to find the first and all elements

    Do you want all the elements or just the first? If you want all, you can use Array.filter. If you want just the first you can use find.

    const fruits = ['apple', 'banana', 'cherry', 'dates', 'fig']
    var func = (val) => { return val.indexOf('e') != -1};
    let matches = fruits.filter(func);
    console.log("all: " + JSON.stringify(matches));
    
    console.log("find: " + fruits.find(func));
    Login or Signup to reply.
  2. You can try this:

    const fruits = ['apple', 'banana', 'cherry', 'dates', 'fig']
    const result = fruits.filter((alpha) => (alpha.includes('e') || alpha.includes('E')))
    console.log(result)
    

    .filter() will return all the that elements match the condition passed. The original array won’t be modified.

    .includes() will return true if the string contains the string passed to the function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search