Accessment for Test your skills: Arrays 3 and 4 JavaScript

Link to source code: Arrays 3
On line 10, I wondered why we needed to add [index] to myArray since newArray on line 9 holds the element and the index altogether.

Link to source code: Arrays 4
Final answer has "Emus,Egrets" as expected but still has "Eagles,Emus,Egrets" using MDN interactive editors which can get confusing and make you feel like there’s something wrong if you’re not using other online editors

1 Like

Very well done, James!

We needed it because we were asked to modify the original myArray array. We loop through each element and change it so it includes its index inside a pair of parentheses. Although newArray is storing the modified value as a string, the original element hasn’t been updated yet. That’s where the second line comes into play: we’re essentially saying “As you loop, set the current element to this new value”. The current element is accessed by its index.

Your solution is as good as it gets. May I suggest a slight modification?

myArray.push("Jems", "Eva");
myArray.forEach((e, i, a) => {
  a[i] = `${e} (${i})`;

It does the exact same thing, only on one line. With the third parameter, you can access the array itself during the loop (see Array.prototype.forEach()). Comes in handy when you want to mutate the original array!

Hmm, it works for me:


@KBar Thanks for the modification, that was helpful …

@KBar I must have mistakenly played or mess with the part of
// Don't edit the code below here

But thanks for your response. It’s amazing