I am trying to solve this problem where if age > 18 it returns name + can go to the matrix or if age < 18 returns they are under age:
function makeStrings(arr){
// your code here
}
console.log(makeStrings([
{
name: "Angelina Jolie",
age: 80
},
{
name: "Eric Jones",
age: 2
},
{
name: "Paris Hilton",
age: 5
},
{
name: "Kayne West",
age: 16
},
{
name: "Bob Ziroll",
age: 100
}
]));
// ["Angelina Jolie can go to The Matrix",
// "Eric Jones is under age!!",
// "Paris Hilton is under age!!",
// "Kayne West is under age!!",
// "Bob Ziroll can go to The Matrix"]
The exercise is from a list of array.prototype.map() exercises so although I think there are other ways to get the correct answer I’ve tried to use the map() method. So far all I’ve managed to get back is a syntax error or [undefined,undefined,undefined,undefined,undefined] which is what the code below returns.
function makeStrings(arr){
// your code here
const map1 = arr.map((person) => {
if(person.age > 18){
person.name + " can go to The Matrix";
}
else {
person.name + "is underage!!";
}
});
return map1;
}
console.log(makeStrings([
{
name: "Angelina Jolie",
age: 80
},
{
name: "Eric Jones",
age: 2
},
{
name: "Paris Hilton",
age: 5
},
{
name: "Kayne West",
age: 16
},
{
name: "Bob Ziroll",
age: 100
}
]));
// ["Angelina Jolie can go to The Matrix",
// "Eric Jones is under age!!",
// "Paris Hilton is under age!!",
// "Kayne West is under age!!",
// "Bob Ziroll can go to The Matrix"]
>Solution :
You can use map()
to transform the array of objects. However, there’s a small mistake in your callback function. You’re not returning the string in your map()
callback.
Here’s the corrected code:
function makeStrings(arr){
const map1 = arr.map((person) => {
if(person.age > 18){
return person.name + " can go to The Matrix";
}
else {
return person.name + " is under age!!";
}
});
return map1;
}
In your original code, you were missing the return
statement before person.name + ...
, so the map callback didn’t return anything, resulting in undefined
.
With this corrected code, when you run makeStrings
with the provided array, you should get the desired output:
[
"Angelina Jolie can go to The Matrix",
"Eric Jones is under age!!",
"Paris Hilton is under age!!",
"Kayne West is under age!!",
"Bob Ziroll can go to The Matrix"
]