Javascript Iterators - secretMessage


#1

I’m trying to find the secretMessage, which I understand is found by taking the first character in each string of the array.

I copied the code in the example:

let numbers = [1, 2, 3, 4, 5];

let bigNumbers = numbers.map(function(number) {
return number * 10;
});


My code looks like the example by returns and error. What am I doing wrong?

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

let secretMessage = (function(charAt(0))
{
return charAt[0];
});


THE ERROR MESSAGE:
let secretMessage = (function(charAt(0))
^


#2
let secretMessage = (function(charAt(0))   // issue is here
{
return charAt[0];
});
let secretMessage = function (list) {
    let message = "";
    for (let x of list) {
        message += x.charAt(0);
    }
    return message;
};
console.log(secretMessage(animals));

The above is how we would solve this using a for-of loop, but being as this is a lesson about iterators it would be more appropriate to apply one.

.map()

How would we assign the secret message to the variable, rather than write it as a function?

 let secretMessage = animals.map(...);

Using the hint above, fill in the missing bits (…).


#3

Ok. thanks, mtf!
Your code using the for-of loop looks difficult (to me)

the code should read:
let secretMessage = animals.map(animal => animal.charAt(0));

I’m beginning to understand, if I look at the correct code and unpack it.

much obliged!
Cecilia D.


#4

Everything new can seem daunting. Nothing a little review won’t fix…

Vanilla JavaScript for

var message = [];
for (var i = 0; i < animals.length; i++) {
  message.push(animals[i].charAt(0));
}
console.log(message.join(''));

ES5.1 forEach

message = "";
animals.forEach (function (x) {
  message += x[0];
});
console.log(message);

ES5.1 Array.prototype.map

message = animals.map(animal => animal[0]).join('');
console.log(message);

ES 2015 for…of

message = "";
for (let x of animals) {
  message += x[0];
}
console.log(message);

[Edit: Arrow functions were not supported yet when .map() was initially defined.]

message = animals.map(function (animal) {return animal[0]}).join('');
console.log(message);

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.