Reputation: 23
I'm brand new to this so if I'm not explaining the problem as I should, please let me know!
I'm basically using Twilio Quest as a way to start learning Javascript and have gotten myself a little stuck.
The challenge is to test the conditions of an array of strings and increase the value of a variable every time a certain string appears ... then return the value of said variable at the end of the function.
Here's what I have:
let freightItems = ['contraband', 'clear', 'contraband', 'clear'];
freightItems.forEach(scan);
function scan(freightItems) {
const contrabandCount = 0;
if (freightItems.element == 'contraband') {
contrabandCount + 1;
}
return contrabandCount;
}
The error I'm getting when I submit the code to TwilioQuest is:
Your function returned a number, but not the value we were looking for. Your function should examine every item in the input array, and return the total number of times the string "contraband" appeared.
Upvotes: 1
Views: 1419
Reputation: 29314
Couple of problems in your code:
you should iterate over the array inside the scan
function because you can't return contrabandCount
variable like you are trying to. Move the forEach
loop inside the scan
function
change
contrabandCount + 1;
to
contrabandCount = contrabandCount + 1;
because you need to update the contrabandCount
variable with the result of contrabandCount + 1
let freightItems = ['contraband', 'clear', 'contraband', 'clear'];
function scan(freightItems) {
let contrabandCount = 0;
freightItems.forEach(str => {
if (str === 'contraband') {
contrabandCount = contrabandCount + 1;
}
})
return contrabandCount;
}
console.log(scan(freightItems))
Upvotes: 3
Reputation: 4474
This can be a solution
let contrabandCount = 0;
let freightItems = ['contraband', 'clear', 'contraband', 'clear'];
freightItems.forEach(el => {
if (el === 'contraband') {
contrabandCount++;
}
});
console.log(contrabandCount);
If you're not forced to use a forEach:
let freightItems = ['contraband', 'clear', 'contraband', 'clear'];
let contrabandCount = freightItems.filter(el => el === 'contraband').length
console.log(contrabandCount);
Upvotes: 0