Hello there ,
I have just finished working with JSON skill test and I need an assessment for my code. Here are the Code pen link & Task link.
Thank you in Advance,
Dinesh
Hello there ,
I have just finished working with JSON skill test and I need an assessment for my code. Here are the Code pen link & Task link.
Thank you in Advance,
Dinesh
Hi @Dinesh_Sake
Well done, again.
Here are some comments:
The last mother cat name should have an “and” before it, and a full stop after it. How do you make sure this can work, no matter how many cats are in the JSON?
total
and male
.++
(e.g. male++;
)I’m curious about your improvements.
Happy coding,
Michael
Hello sir, I’ve changed the code according to your comments, but I’m unable to insert “add” before the last word. I have tried several methods and none of them are working properly, I would really appreciate your help with this.
Thank you,
Dinesh
The counting is fine now.
Regarding the sentence you need a if..else
statement and it would help to use a traditional for
loop, because we can use the index in the condition:
if (<condition>) {
motherInfo += `${ cats[i].name }, `;
} else {
motherInfo += `and ${ cats[i].name }.`;
}
The <condition>
needs to be true
as long as we are not in the last loop. To do this we need to compare the index with cats.length
.
Okay Sir, I have done the changes, please check for any errors.
Thank you,
Dinesh
Okay, now it works.
Another possibility instead of writing a second loop would have been rewriting for (const cat of cats){
to for (let i = 0; i < cats.length; i++){
and put all the code into the same loop.
By the way: You sliced the last two letters of the last cat. It should be “Antonia”.
This would be a single loop that does all the work:
for (let i = 0; i < cats.length; i++) {
for (const kitten of cats[i].kittens) {
total++;
if (kitten.gender === 'm') {
male++;
}
}
if (i < (cats.length - 1)) {
motherInfo += `${ cats[i].name }, `;
} else {
motherInfo += `and ${ cats[i].name }.`;
}
}