Lesson 3 in Iterator, using map(). Is my code wrong?

let animals = [‘Hen’, ‘elephant’, ‘llama’, ‘leopard’, ‘ostrich’, ‘Whale’, ‘octopus’, ‘rabbit’, ‘lion’, ‘dog’];

// Create the secretMessage array below
let secretMessage = animals.map(function(animal) {
return animal.slice(0,1);
});

console.log(secretMessage.join(’’));

let bigNumbers = [100, 200, 300, 400, 500];

// Create the smallNumbers array below
let smallNumbers = bigNumbers.map(number => number / 100);

console.log(smallNumbers);

Are you getting an error message from the lesson checker?

I’m not sure if .slice() has been covered yet, so that may raise a flag, even though the solution works.

We can also use,

String.charAt()

String[0]

No, I don’t get error. The result shows true, but the system detects error.

So, I change using method charAt(0) and it works.

1 Like

let animals = [‘Hen’, ‘elephant’, ‘llama’, ‘leopard’, ‘ostrich’, ‘Whale’, ‘octopus’, ‘rabbit’, ‘lion’, ‘dog’];

// Create the secretMessage array below
let secretMessage = animals.map(function(animal){
return animal[0];
});

I’m trying to understand the difference between map() and forEach(). When does one use one over the other? Presumably both take each element in the array and does what ever you put in the function for each element and returns an array. Can some one else explain the difference? Thanks.

Not so in the case of forEach, it does not return anything.

array = [2, 4, 6, 8, 10]
array.forEach(x => console.log(x - 1))
1
3
5
7
9
console.log(array)
// [2, 4, 6, 8, 10]
newArray = array.map(x => x - 1)
console.log(newArray)
// [1, 3, 5, 7, 9]

There are other use cases but the above gives us the gist. When we wish to only perform an action and not return any data, such as logging like above, then forEach is the iterator to substitute in the place of a for loop. When we wish to transform the data into a new array, then map is the iterator to reach for.