Help with Array methods in JS

Problem #1:
I have this array:
const birds = [ “Parrots”, “Falcons”, “Eagles”, “Emus”, “Caracaras”, “Egrets” ];

I’d like to create a copy of this array that includes birds that start with the letter E. How would you go about this?

Problem #2
I have this array:
let myArray = [ “Ryu”, “Ken”, “Chun-Li”, “Cammy”, “Guile”, “Sakura”, “Sagat”, “Juri” ];

How would I go through each item and add the index of the item in paranthesis? I tried using a forEach loop:

myArray.forEach((item, index) => item = item + ‘(${index})’)

But nothing happens!

Thank you.

problem 1
-create a new empty array where you will store all elements that start with ‘e’
-Use the array.forEach() method , array.map() method or for…of loop to cycle through every element in the array.
-For every element, check whether the first character in the string is equal to the first letter (you can first convert to upper/lowercase depending on whether you like it to be case sensitive or not), then push to the array above if true.

const birds = [ “Parrots”, “Falcons”, “Eagles”, “Emus”, “Caracaras”, “Egrets” ];
const newarray = []
birds.forEach(element => {
if(element.charAt(0)===‘K’) {
newarray.push(element)
}
})

Problem 2
Like in the previous solution, create a new empty array and push each element into it after adding the character you wanted to add.

let myArray = [ ‘Ryu’, ‘Ken’, ‘Chun-Li’ ];
let newarray = []
myArray.forEach((element,index) => {
newarray.push(element+${index})
})

forEach() does not mutate the array on which it was called, unless you pass a function to it as an argument, which is why your approach did not work.

2 Likes

Hello @steviesteve and @mash and welcome to the community :wave:

Additionally to what Ian said (Thank you!):

In task1 you could also use String.prototype.startsWith() and Array.prototype.filter()

In task 2 the reason why your code doesn’t work is because you can’t directly assign to item. You would need to do something like that:

myArray[index] = `${item} (${index})`

Have a nice day,
Michael

PS: @steviesteve Your email address is visible in your post. I think it somehow ended up in the optional “name” field of your profile. I recommend removing it.

1 Like