Home > Enterprise >  TwilioQuest Javascript Problem: Constant Vigilance
TwilioQuest Javascript Problem: Constant Vigilance

Time:04-20

This is my first post, began learning js about a couple of weeks ago and am about 8 hours in! I'm aware of a very similar question with a good answer, but I'm trying to understand why what I've done is wrong.

OBJECTIVE: This function should take a single argument - an array of strings. Your scan function must loop through all the strings in this array, and examine each one using boolean logic.

If a string in the input array is equal to the value contraband, add the index of that item to an output array. When you have finished scanning the entire input array, return the output array, which should contain all the indexes of suspicious items in the array.

For example, given an input array of:

['contraband', 'apples', 'cats', 'contraband', 'contraband'] Your function should return the array:

[0, 3, 4] This list contains the position inside the input array of all the contraband strings.

function scan(freightItems) {
let contrabandIndexes = [];
  for (let index in freightItems)
  if (freightItems == 'contraband') contrabandIndexes.push(index);

return contrabandIndexes;
}

const indexes = scan(['dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Contraband Indexes: '   indexes); // should be [1, 4]

I keep getting the output "Conrtraband Indexes: " when I should be getting "Contraband Indexes 1, 4"

Please help!

CodePudding user response:

There is a typo in the code of yours. I assume it should be

...
for (let index in freightItems) 
if (freightItems[index] == 'contraband') // comparison of a value taken by index over comparing the whole array 
...

Please note that the for...in loop is not a preferable choice for arrays iteration ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#array_iteration_and_for...in )

CodePudding user response:

The below code uses forEach.

function scan(freightItems) {
  let contrabandIndexes = [];
  freightItems.forEach((element, index) => {
    if (element == 'contraband') contrabandIndexes.push(index);
  })
return contrabandIndexes;
}

const indexes = scan(['dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Contraband Indexes: '   indexes); // should be [1, 4]

Output: 'Contraband Indexes: 1,4'

Or modifying your code with a few changes

function scan(freightItems) {
let contrabandIndexes = [];
  for (let index in freightItems) {
    if (freightItems[index] == 'contraband') contrabandIndexes.push(index);
  }

return contrabandIndexes;
}

const indexes = scan(['dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Contraband Indexes: '   indexes); // should be [1, 4]

Output: 'Contraband Indexes: 1,4'

  • Related