The TwilioQuest JavaScript Challenge: Unwavering Alertness

Just starting out with JavaScript and I've been learning for a couple of weeks, putting in about 8 hours so far. I know there's a similar question out there with a good answer, but I really want to understand why my approach isn't working.

TASK: The goal of this function is to take an array of strings as input. Your scan function should iterate through all the strings in the array, examining each one using boolean logic.

If a string in the input array matches the value 'contraband', the index of that item should be added to an output array. Once you have scanned the entire input array, return the output array containing the indexes of suspicious items.

For example, if the input array is:

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

[0, 3, 4] This list shows the positions of all contraband strings within the input array.

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]

Currently, I'm getting the output "Conrtraband Indexes:" instead of "Contraband Indexes 1, 4"

I would appreciate any help or guidance on this issue!

Answer №1

There seems to be a mistake in your code that needs fixing. It appears that the correct version should look like this:

...
for (let index in freightItems) 
if (freightItems[index] == 'contraband') // comparing individual values instead of the whole array
...

It's important to remember that using for...in loops for iterating through arrays is not considered best practice ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#array_iteration_and_for...in )

Answer №2

This code snippet demonstrates the usage of forEach method in JavaScript.

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); // expected output: [1, 4]

Output: 'Contraband Indexes: 1,4'

You can also achieve similar functionality by modifying the code as follows:

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); // expected output: [1, 4]

Output: 'Contraband Indexes: 1,4'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Quick and easy way to access json data with jquery

https://i.sstatic.net/kiEwe.png Need help with reading data from JSON format using jQuery. I've attempted the code below, but I'm having trouble retrieving the exact data I need. $.ajax({ url: '@Url.HttpRouteUrl("GetDistrictLi ...

React - retrieving the previous page's path after clicking the browser's "back" button

Imagine I'm on Page X(/path-x) and then navigate to page Y(/path-y). Later, when I click the "back" button in the browser. So my question is, how do I retrieve the value of /path-y in PageX.tsx? Note: I am utilizing react-router-dom ...

I seem to be encountering an issue with storing data properly within the for loop - can anyone point out where I may

Within my code, I am iterating through results.data.data.length and successfully retrieving the correct data while storing it appropriately. The data: param1 = [6, 27, 34, 22, 23, 25, 28, 24, 26, 30, 29] // => array length 11 The issue arises when att ...

What could be the reason for operators like tap and map not being invoked on the inner observable when combineLatest is used?

Can you clarify why the operators tap and map of inner observable are not being called? Shouldn't combineLatest subscribe to the observables it receives in obsArr? Why are these operators not triggered by this subscription? const obsArr = []; [[1, 2 ...

NodeJS application experiencing significant delays due to slow response times from MySQL database queries

Currently, I am in the process of learning about Node.js. Through utilizing Express and Node-Mysql, I have been able to effectively query my mysql database and return the outcomes as JSON to the client. However, there seems to be a significant delay. Eve ...

Is there a way to access the state value within the reducer function of createSlice?

Currently, I am utilizing redux-toolkit within my react project. A concern arises in a specific reducer inside the createSlice method where I aim to incorporate an existing array of entities from the state and then merge it with a new array before finalizi ...

Transferring Data to EJS Template

I have been facing a challenge in passing a value from a POST route to an EJS file for display. Despite trying various methods like redirecting, sending, and rendering the results, the data won't make its way to the EJS file. Below is the POST route ...

Attempting to resolve an error message with the help of JQuery

I need help figuring out how to clear an error icon when a user presses a key. ** EDIT - including the HTML code ** <input class="validate" type="text" data-type="string" id="address" /> <input class=" ...

How to swap out the rel attribute with id in jQuery

Ensuring my webpages are W3C valid is a priority for me. I am taking steps to rectify errors one by one in order to achieve validity. Upon using the HTML5 doctype, an error was flagged. On Line 348, Column 81: it was pointed out that the RDFa Core attribu ...

Steps to update the package version in package.json file

If I remove a package from my project using the following command: npm uninstall react The entry for this package in the package.json file does not disappear. Then, when I install a different version of this package like so: npm install <a href="/cdn ...

When adding an object to an array in AngularJS, it seems to trigger updates for

Currently, I am fetching data from a WebAPI and then storing it in an array called products, which is scoped. $scope.products In addition to the products array, I also have another scoped array named selectedFish. $scope.selectedFish = []; My objective ...

Strip all textual content from within HTML div elements while retaining the original HTML tags and formatting

I currently have the following HTML code: <div> Here <a href="#"> is </a> <p> Text, that I want to </p> be removed </div> This is what I desire: <div> <a href="#"> </a> <p& ...

Seeking out all of the children associated with their parent using Jquery

Currently, I am utilizing Codeigniter and Jquery in conjunction with the AJAX method to retrieve data from two tables within my database by using a select join operation on the 'group' table and 'cat' table. Below is a description of t ...

Creating a never-ending scroll feature on a static page in Next.js

I am in the process of creating a portfolio using Next.js and have a large number of projects on the page. I would like to implement a feature where images start loading only when they enter the current viewport. This functionality works well with the defa ...

Encountering a "Can't find variable" error in Java when using Ghostdriver 1.2.1 with PhantomJS 2.0 and the newest version

[ALERT - 2016-01-16T02:22:00.898Z] Session [e6651a90-bbf7-11e5-9061-cff578894101] - page.onError - msg: ReferenceError: Can't find variable: data :262 in error [WARNING - 2016-01-16T02:22:00.898Z] Session [e6651a90-bbf7-11e5-9061-cff578894101] ...

AngularJS controller function fails to trigger

I have three directives, "parenta", "parentb", and "childb". The first two are siblings while the third one is a direct child of "parentb". When attempting to call a controller method from "parenta", it does not work. Strangely, calling a method on the "c ...

What is the best way to retrieve information from a form that is coded within inner HTML?

I need to extract data from the text fields in my code. How can I do that? Here is my JavaScript function that adds a new form every time the add button is clicked: function elementAppender() { if (count <= 5) { let element = docum ...

Assigning a background image based on the quantity of items in an array or object

I'm having trouble appending divs and setting their background image based on the number of items in an array or object. Despite adding the divs correctly, all of them end up with the same background image when only three should have it. Can someone e ...

The propagation of onClick events in elements that overlap

Having two divs absolutely positioned overlapping, each containing an onClick handler. The issue is that only the top element's onClick handler fires when clicked. React 17 is being used. Here is some sample code: <div style={{ position: "abs ...

Modify the width of a div element by clicking on it using Javascript

I need to achieve three tasks onclick: change the display:none property of the element with id="notes_content" to display: block modify the width of the element with id="oct" from 1190px to 550px update the width of elements with class="oct_days" from ...