Reputation: 27
I'm writing a function for a game called TwilioQuest. The function neeps to loop through each item in the freightItems
array (already defined by TwilioQuest) and count each time the item 'contraband'
is noticed. I created an array after the function to test the code.
The problem I'm having is that the function doesn't seem to be able to discriminate between the item 'contraband' and any other item. When the contrabandCount
is returned, it displays "5"
instead of the expected "2". Can anyone help me understand where I went wrong?
Here's my code:
function scan(freightItems) {
let contrabandCount = 0;
freightItems.forEach(function(freightItems) {
if ('contraband') contrabandCount++;
});
return contrabandCount;
}
const numItems = scan(['dog', 'contraband', 'cat', 'zippers',
'contraband'
]);
console.log('Number of "contraband": ' + numItems)
Upvotes: 1
Views: 64
Reputation: 2870
Maybe an improved Syntax :
With forEach
:
function scan(searchabelItem, freightItems, contrabandCount = 0) {
freightItems.forEach((value) => value === searchabelItem && contrabandCount++)
return contrabandCount;
}
With filter
:
function scan(searchabelItem, freightItems, contrabandCount = 0) {
freightItems.filter((value) => value === searchabelItem && contrabandCount++)
return contrabandCount;
}
Upvotes: 0
Reputation: 4572
Filter method is all you need
const numItems = ['dog', 'contraband', 'cat', 'zippers', 'contraband'];
var filtered = numItems.filter(x => x == 'contraband');
console.log('Number of "contraband": ' + filtered.length);
You can use this sintax if you want, remember compare freightItems with 'contraband'
function scan(freightItems) {
let contrabandCount = 0;
freightItems.forEach((freightItems) => {
'contraband' === freightItems ? contrabandCount++ : 0;
});
return contrabandCount;
}
Upvotes: 0
Reputation: 9301
function scan(freightItems) {
let contrabandCount = 0;
freightItems.forEach(function(entry) {
if (entry == 'contraband') {
contrabandCount++;
}
});
return contrabandCount;
}
const numItems = scan(['dog', 'contraband', 'cat', 'zippers',
'contraband'
]);
console.log('Number of "contraband": ' + numItems)
Upvotes: 1
Reputation: 510
you need to compare the freightItems
value to "contraband"
freightItems.forEach(function(freightItem) {
if(freightItem === 'contraband')
contrabandCount++
})
Upvotes: 3