JavaScript: accessing elements in an array

When inputting "12314" into the 'word' string below, everything functions correctly. However, if I enter characters like "abacd", the code encounters an error. Does anyone know why this might be happening? (1 in [1,2,3,1,4]) yields the correct result, but ('a' in [a,b,a,c,d] fails. I am still learning Javascript and would appreciate any insights.

var word = "abacd";

function duplicateEncode(word){

  var repeat = [];
  var result = [];
  var letters = word.split('');

  for (i=0; i < letters.length; i++){
    if (letters[i] in repeat) {
        result.push(")");
    } else {
        result.push("(");
    }
    repeat.push(letters[i]);
  }
  return result;
}

Answer №1

in operator:

A string or symbol representing a property name or array index (non-symbols will be coerced to strings).

Your situation works because it focuses on the index rather than the value of the string. When 'in' operator is used on an array, it considers the index as the properties.


Experiment with this:

> 1 in [1,2] //-> true
> 1 in [1]   //-> false (only one item in the list)
> 1 in [2,2] // -> true


> Object.keys([2,3,4])  // -> ['0', '1', '2' ]
// In your case, you should use indexOf instead
>['a','b','c'],indexOf('a') -> 0
>['a','b','c'],indexOf('e') -> -1

To resolve your problem, replace in with:

for (i=0; i < letters.length; i++){
 if (repeat.indexOf(letter[i]) > -1) {
    result.push(")");
 } else {
    result.push("(");
 }
 repeat.push(letters[i]);
}

Answer №2

Take a look at this code snippet...

function encodeDuplicates(input){

  var repeatedChars = [];
  var resultArray = [];
  var characters = input.split('');
  
  for (var i=0; i < characters.length; i++){
      if (repeatedChars.indexOf(characters[i]) != -1) {
          resultArray.push(")");
      } else {
          resultArray.push("(");
      }
      repeatedChars.push(characters[i]);
   }
   
   return resultArray;
}

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

React Table in Modal Using Custom Hook State

I'm facing some difficulties with the React useState hook. Currently, I have a modal that pops up after submitting a form. Before loading the modal, the application calls an API to fetch data, which is then displayed in a table within the modal. The ...

Tips for selecting a radio button using its unique identifier

I'm having trouble getting this code to work properly. I can't seem to find any mistakes in the code, can someone please assist me in resolving this issue? <html> <body> <input type="radio" name="radio" id="radio1">Site 1< ...

The setValue change function in Bootstrap-slider.js does not get triggered when called programmatically

I've incorporated bootstrap-slider.js into my project and everything seems to be working smoothly. However, I've encountered an issue with setting a new value using the setValue function, as it does not seem to trigger the associated "change" fun ...

Using Jquery to insert new rows into a table

Here is the code for my button and table: <button type="button" class="btn btn-md" id="addRowBtn">Test Button To Add Row</button> <table id="tableForRows"> <tr> <td> </td> </tr> </tabl ...

Verify the presence of the input post in the mongo database

Currently, I am utilizing the following node js code to store data in a database... //connect to database db.on('error', console.error); db.once('open', function() { router.post('/register', function(request, response) { ...

Changing object in Vuex mutation - a step towards state update

When a button is clicked by the user, I aim to update the data in my vuex store with the information from my local object. However, I am facing an issue with the mutation process. Below you can find some code snippets for better understanding. The followi ...

Unable to conceal element if it is devoid of content

<div id="web-link" class="infoline"> <i class="fa fa-link fa-2x fa-fw coloriconfa"></i> <a href="<?=$data['post']['url']?>" target="_blank"><?=$data[ ...

What is the Vue.js alternative to setTimeout?

I'm currently in the process of developing a shopping cart feature using Laravel and Vue. In my system, when an item is added to the shopping basket, I want to display a confirmation message by toggling a Vue variable that is being monitored through a ...

Issue with implementing an if statement in a function using JQUERY

I have a function that detects changes in a checkbox. Upon page load, the checkbox may be checked or unchecked based on previous actions. I am looking to keep track of whether the checkbox has been modified. If the checkbox is changed and then changed bac ...

Undefined reference to Kendo UI Grid in AngularJS was encountered

Recently, I've been working on integrating Kendo UI with AngularJS. Despite being new to AngularJS, I'm trying my best to follow the guidelines. However, I've encountered an issue that I can't seem to solve - I am unable to obtain a ref ...

Adding inline SVGs to a Nuxt 3 Vite project: A step-by-step guide

Hey there, I've been struggling with importing inline SVGs into my Nuxt3 Vite project. Any advice would be greatly appreciated. I discovered that using <img src="~/assets/images/icons/push-icon-chatops.svg" /> works, but I actually ne ...

Unable to locate an element on the webpage due to a JavaScript-based error, which then becomes hidden after a few seconds. (Registration form)

While completing a registration form, I encounter a hidden message after clicking on the register button. Struggling to locate this elusive element has been an ongoing challenge for me. Unfortunately, my attempts to find the element have been unsuccessful ...

The event emitted doesn't appear to be caught by EventBus.$on in Vue.js

Currently trying to trigger an event from router.beforeEach and listening for it in another component. Although the vue devtool confirms that the event is being triggered, my component seems unable to capture it. Thank you for your help. This is how I dec ...

Utilizing auto-generated Nonce for Content Security Policy in a Node.js/Express web application

I've exhausted all possible solutions in my attempt to create a nonce and pass it successfully to the CSP and inline scripts with the nonce variable. Despite reading numerous articles, the guidance on accomplishing this task remains vague. Fortunately ...

Ways to apply Position Fixed to a particular Div element and subsequently eliminate that class while scrolling

Check out my current Jsfiddle project here I am working on a task that involves adding a class to a specific div when scrolling and then removing that class. Below is the JavaScript code I have written for this functionality: var targetDiv = $(".mainwra ...

Combining objects in React: An exploration of array merging

I have an array of objects that look like this: [{ a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, …],[{ a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, …],[{ a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, …] My goal is to merge them into one unique array as ...

Retrieve the offspring with the greatest level of depth within a parental relationship

Consider the following tree structure: -root | | |-child1 | |-innerChild1 | |-innerChild2 | |-child2 I am looking to create a JavaScript function that can determine the depth of an element within the tree. For example: var depth = getInnerDepth( ...

Timetable sets anchors raised

Is there a way to set up regular sail lifts? For instance, can sails be scheduled to restart every 12 hours? I am looking to do this to prevent losing connection to the remote database. Thank you ...

Creating a simulated float:top effect in JavaScript

Is there a way to achieve a css float:top attribute in javascript, either using native code or jQuery? I have a large list of items that I want floated, stacking them top to bottom and left to right. Currently, floating them left stacks them left to right ...

The property 'map' cannot be read as it is undefined when outside the scope of page.evaluate()

Here is a code snippet to consider: let foo = await page.evaluate( () => { let bar = [...document.querySelectorAll(".foobar")]; return bar.map((u) => u.textContent.trim()); } ); foo.forEach((u) => { console.log(u); }); Now let's ...