Array startsWith() method

While I select strings that start with “E” from the array, still other string commas show up. How can I fix it? Thanks for helping in advance.

const birds = [ “Parrots”, “Falcons”, “Eagles”, “Emus”, “Caracaras”, “Egrets” ];

// Add your code here

let index = birds.indexOf(“Eagles”);

if (index !== -1) {
birds.splice(index, 1);
}

function nameFun(name) {

if (name.startsWith(“E”)){
return name;
};
};

const eBirds = birds.map(nameFun);

// Don’t edit the code below here!

section.innerHTML = ’ ';

const para1 = document.createElement(‘p’);
para1.textContent = eBirds;

section.appendChild(para1);

1 Like

you should use ‘filter’.

const eBirds = birds.filter(nameFun);

3 Likes

Welcome to the community @Elvin_Hatamov and @xu_zhang! xu_zhang is correct! Using the filter function would return the results you were expecting.

The map function will run the function on each element but, will still return all elements of the original array. Currently, the nameFun has an implicit(default) return of undefined if the condition did not match.

If you return something else the output might be a little more intuitive. For example:

function nameFun(name) {
  if (name.startsWith("E")) {
    return name;
  } // also note that you do not need a `;` here

  return "no match";
}

Note, that when using filter you actually want the default undefined return from nameFun as that will ensure that the word is filtered out.

2 Likes

Thanks for your comment very informative and helped me.

1 Like