Goot_Warren
Goot_Warren

Reputation: 23

checking array strings with foreach in javascript

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

Answers (2)

Yousaf
Yousaf

Reputation: 29314

Couple of problems in your code:

  1. 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

  2. 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

Balastrong
Balastrong

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

Related Questions